How to Add Multiple Forms on One Page View in Django

Django is a powerful and versatile web framework for building web applications in Python. One common requirement in web development is to have multiple forms on a single page view. Whether you want to collect various types of user input or handle different aspects of a task, Django provides a straightforward way to achieve this. In this blog post we’ll explore how to add multiple forms on one page view in Django.

Why Multiple Forms on One Page?

Before diving into the technical details, let’s understand why you might want to have multiple forms on a single page view in your Django project:

  1. User Experience: It can improve the user experience by reducing the number of page reloads or navigation steps required to submit different types of information.
  2. Efficiency: When dealing with related data, such as a user’s profile information and their avatar upload, having them on the same page simplifies the workflow.
  3. Consistency: Keeping forms on one page can maintain a consistent look and feel, enhancing the overall design of your web application.

Implementation

Now, let’s proceed to implement multiple forms on a single page view in Django:

Step 1: Create Your Django Project

If you haven’t already set up your Django project, you can create one using the following commands:

django-admin startproject project_name
cd project_name
python manage.py startapp app_name

Step 2: Define Your Forms

In Django, you can create forms using Django’s built-in forms module. Create multiple forms as needed in your app’s forms.py file. For example, let’s create two forms: UserProfileForm and AvatarUploadForm.

# app_name/forms.py
from django import forms

class UserProfileForm(forms.Form):
    username = forms.CharField(max_length=100)
    email = forms.EmailField()

class AvatarUploadForm(forms.Form):
    avatar = forms.ImageField()

Step 3: Create a View

Now, create a view in your app’s views.py file that will render the page with multiple forms. You can use Django’s TemplateView as a base class and pass the forms to the template context

# app_name/views.py
from django.views.generic import TemplateView
from .forms import UserProfileForm, AvatarUploadForm

class MultiFormView(TemplateView):
    template_name = 'multi_form.html'

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['user_profile_form'] = UserProfileForm()
        context['avatar_upload_form'] = AvatarUploadForm()
        return context

Step 4: Create a Template

In your app’s templates directory, create an HTML template (multi_form.html) to render the forms.

<!-- app_name/templates/multi_form.html -->
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Multiple Forms Example</title>
</head>
<body>
    <h1>User Profile Form</h1>
    <form method="post" enctype="multipart/form-data">
        {% csrf_token %}
        {{ user_profile_form.as_p }}
        <button type="submit">Submit Profile</button>
    </form>

    <h1>Avatar Upload Form</h1>
    <form method="post" enctype="multipart/form-data">
        {% csrf_token %}
        {{ avatar_upload_form.as_p }}
        <button type="submit">Upload Avatar</button>
    </form>
</body>
</html>

Step 5: Define URL Patterns

Finally, define URL patterns in your app’s urls.py to map the view to a URL

# app_name/urls.py
from django.urls import path
from .views import MultiFormView

urlpatterns = [
    path('multi-form/', MultiFormView.as_view(), name='multi_form_view'),
]

Step 6: Run the Development Server

Now, you can run the Django development server using the following command:

python manage.py runserver

Visit http://127.0.0.1:8000/app_name/multi-form/ in your web browser to see your multiple forms on one page.

How to Submit Multiple Forms on One Submit Button in Django

In Django, you can submit multiple forms on one page using a single submit button.. To achieve this, we’ll modify our previous example to handle form submissions and demonstrate how to process the data from each form. Let’s go through the steps

Step 1: Update the View

In your app’s views.py, update the view to handle form submissions. We’ll check if the request is a POST request and then validate and process each form accordingly.

# app_name/views.py
from django.views.generic import TemplateView
from .forms import UserProfileForm, AvatarUploadForm

class MultiFormView(TemplateView):
    template_name = 'multi_form.html'

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['user_profile_form'] = UserProfileForm()
        context['avatar_upload_form'] = AvatarUploadForm()
        return context

    def post(self, request, *args, **kwargs):
        user_profile_form = UserProfileForm(request.POST)
        avatar_upload_form = AvatarUploadForm(request.POST, request.FILES)

        if user_profile_form.is_valid() and avatar_upload_form.is_valid():
            # Process data from the user profile form
            username = user_profile_form.cleaned_data['username']
            email = user_profile_form.cleaned_data['email']

            # Process data from the avatar upload form
            avatar = avatar_upload_form.cleaned_data['avatar']

            # Now you can perform any necessary actions with the data

            # For demonstration purposes, we'll just print the data
            print(f"Username: {username}")
            print(f"Email: {email}")
            print(f"Avatar: {avatar}")

            # You can save data to the database, update models, etc., as needed

            # Redirect or render a success page
            return HttpResponse("Forms submitted successfully!")

        else:
            # If any form is not valid, re-render the template with error messages
            return self.render_to_response(self.get_context_data())

Step 2: Update the Template

In the template (multi_form.html), make sure to include the csrf_token and use the correct form tags for each form. Also, include a single submit button for both forms.

<!-- app_name/templates/multi_form.html -->
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Multiple Forms Example</title>
</head>
<body>
    <form method="post" enctype="multipart/form-data">
        {% csrf_token %}
        <h1>User Profile Form</h1>
        {{ user_profile_form.as_p }}

        <h1>Avatar Upload Form</h1>
        {{ avatar_upload_form.as_p }}

        <button type="submit">Submit</button>
    </form>
</body>
</html>

This example demonstrates how to handle multiple forms on one page with a single submission action, allowing you to process data from each form as needed in your Django application.

Conclusion

In this tutorial, we’ve explored how to add multiple forms on one page view in Django. By creating separate forms, defining a view, creating a template, and routing URLs, you can streamline your web application’s user interface and improve user interaction. This approach enhances the overall user experience while maintaining the efficiency and consistency of your application.

Blogs You Might Like to Read!