How to Use Formset in Django?

Published On: 28/10/2022 | Category: Django


Hi Dev,

In this tutorial, I will show you how to use formset in django. I explained simply step by step django formsets example. it's simple example of django formset factory example. I explained simply step by step django dynamic formset example.

Django's Formsets feature is a sophisticated method of managing several forms on a single webpage. In other words, Django Formsets are a collection of forms. For instance, it may be desirable to start several forms on a same page, each of which may require several POST requests.

Here i explained simply step by step example of how to how to create pagination using ajax in django.

Step 1: Create a Project

In this step, we’ll create a new django project using the django-admin. Head back to your command-line interface and run the following command:

django-admin startproject example

Step 2: Create a App

Now we'll create a single app called core to store a list of post names. We're keeping things intentionally basic. Stop the local server with Control+c and use the startapp command to create this new app.

python3 manage.py startapp core

Step 3: Update setting.py

Then update INSTALLED_APPS within our settings.py file to notify Django about the app, in setting.py file so our setting file look like this..

settings.py
....
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'core',

]

Step 4: Create a Form

In this step We need to create a form that will be used .like add a bootstrap class and validation etc.. plus we need to add custom styling.

core/forms.py
from django import forms

class PostForm(forms.Form):
    title = forms.CharField(label='Title',
                                widget=forms.TextInput(attrs={
                                    'class': 'form-control'
                                })
                            )
    pub_date = forms.DateField(label='Pub Date',
                                widget=forms.TextInput(attrs={
                                    'class': 'form-control'
                                })
                            )

Step 5: Creating the Views

In this step, we need to configure views. The home page will just be a template. function is basically get the all object of article table open the core/views.py file and add:

core/views.py
from django.shortcuts import render
from django.forms import formset_factory
from .forms import PostForm

# Create your views here.
def formset_view(request):
    context ={}
  
    PostFormSet = formset_factory(PostForm, extra = 2)
    formset = PostFormSet(request.POST or None)

    if formset.is_valid():
        for form in formset:
            print(form.cleaned_data)
      
    context['formset']= formset
    return render(request, "form.html", context)

Step 6: Creating the Templates

Next, then with your text editor create new templates files: core/templates/form.html file and the add:

core/templates/form.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Tuts-Station.com</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css">
    <style type="text/css">
        body{
            background-color: #f7fcff;
        }
    </style>
</head>
<body>
    <div class="container mt-5">
        <div class="row d-flex justify-content-center">
            <div class="col-md-10">
                <div class="card">
                    <div class="card-header">
                        <h4>How to Use Formset in Django? - <span class="text-primary">Tuts-Station.com</span></h4>
                    </div>
                    <div class="card-body">
                        <form method="POST" enctype="multipart/form-data">
                            {{ formset.management_data }}
                            {% csrf_token %}
                            {{ formset.as_p }}
                            <input type="submit" class="btn btn-success" value="Submit">
                        </form>
                    </div>
                </div>
            </div>
        </div>
    </div>
</body>
</html>

Step 7: Creating URLs

In this section, we need a urls.py file within the core app however Django doesn't create one for us with the startapp command. Create core/urls.py with your text editor and paste below code.

core/urls.py
from django.urls import path
from . import views

urlpatterns = [
    path('formset', views.formset_view),
]

Next, we require to add a URL path for our example app which can be done by importing include and setting a path for it.

example/urls.py
from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include('core.urls')),
]

Run the Server

In this step, we’ll run the local development server for playing with our app without deploying it to the web.

python manage.py runserver

Next, go to the http://localhost:8000/formset address with a web browser.

I hope it will help you....

Happy Coding!