Single View for Add/Edit in Django

July 22, 2024, 3:11 p.m.

In this blog post, we’ll explore a practical approach to Create Add and Edit in the Same View & Template – Django in a Django application using the same view and rendering it in the same template. This technique is particularly useful when you want to streamline your code and improve user experience.

 

  • Section ID Check: When the view is accessed, it checks if a section ID is provided. If so, it retrieves the corresponding section from the database for editing.
  • Form Submission: Upon form submission, the view processes the data using a SectionForm. If the form is valid, it saves the changes to the database and redirects the user to the add_section view.
  • Form Rendering: If the request method is not POST (i.e., GET), the view renders the form with the section data (if provided) or empty fields for adding a new section.
  • Context Preparation: The view fetches all sections from the database and prepares the context with the form and section data for rendering the template.

 

def add_section(request, section_id=None):
    """
    Add a new section or edit an existing one 
    and render it in the same template
    """
    # Check if a section ID is provided for editing
    section = None  # Initialise with no section
    if section_id:
        try:
            section = Section.objects.get(id=section_id)
        except Section.DoesNotExist:
            raise Http404("Section does not exist.")    # Process form submission
    if request.method == "POST":
        form = SectionForm(request.POST, instance=section)
        if form.is_valid():
            section = form.save()
            return redirect("add_section")
    else:
        form = SectionForm(instance=section)    # Fetch all sections
    sections = Section.objects.all()    # Prepare context for rendering the template
    context = {"form": form, "sections": sections}
    return render(request, "students/sections/add_section.html", context)

Back