Hiya, I’m fairly new in using Django (Only like 3/4 months of self-taught). So sorry if this question seems trivial.
Sooooo I was thinking right, should I make templates for CRUD Operation concise and just have one file to add and edit data or should I have two file where in file add.html is when I add the data, and edit.html is where I edit the data?
Exempli gratia, imagine we have a model class called Crew and we want to have a CRUD operations done in 3 web page;
- See all Crew
- Add new Crew
- Edit or Delete the Crew
If we’re using 1 html templates it’ll show an error of “Reverse for ‘delete-CREW’ with arguments ‘(None,)’ not found.” because the “Delete” parts need an ID, but I have a workaround! See below
class Crew(models.Model):
created_at = models.DateTimeField(auto_now_add = True, blank=True, null=True)
name = models.CharField(max_length=50)
department = models.CharField(max_length=50, blank=True)
company = models.CharField(max_length=50, blank=True)
With two views where in editCrew I’ll have edit = 1 passed in to the templates.
def addCrew(request):
if request.method == "GET":
edit = 0
crewForm = addCrew()
elif request.method == "POST":
edit = 0
crewForm = addCrew(request.POST or None)
return render(request, 'addCrew.html', {'crewForm ' : crewForm , 'edit' : edit})
def editCrew(request, pk):
if request.method == "GET":
edit = 1
crewForm = addCrew(instance = Crew.objects.get(id = pk))
elif request.method == "POST":
edit = 1
crewForm = addCrew(request.POST or None, instance = Crew.objects.get(id = pk))
return render(request, 'addCrew.html', {'crewForm ' : crewForm , 'edit' : edit})
And when in templates, I’ll just do something along the line of
{% if edit == 1 %}
<a href="{% url 'crewDelete' form.instance.id %}">Delete</a>
{% endif %}
So tadaa, one templates with two views. Is it better to do it that way? Or just make two html file? I mean what I was thinking is it’s more concise so I don’t need to change two html file if I want to add or change a feature. And passing one variable wouldn’t hurt right? And sorry if I can’t give a better example, I signed an nda lmao
Thank you in advance for whoever that’ll reply to this!