[Answered ]-What is Django formsets used for?

2👍

Formset is an example of datagrid .
If you want to use multiple form of same type at one page.you can use Formset.
Example :

class UserForm(forms.ModelForm):
    class Meta:
        model = User
        fields = ["username", "email"]

Now if you want to use UserForm multiple times at one page you need to use Formset.

from django.forms.formsets import formset_factory
Uforms = formset_factory(UserForm, extra = 4)  #extra used to define how many empty forms will display

Into Your views.py

def submit(request):
    if request.POST:
        #code to manage post request
        # validation to formset you can follow django docs
    else:
        address_formSet = Uforms(instance=UserForm())
    # render response

Template code

      {{ address_formset.as_table }}

You can follow step by step django formset to learn.

Example Code

class Address(models.Model):
    city = models.CharField(max_length=48)
    zipcode = models.IntegerField(max_length=5)  

class Friend(models.Model):
    name = models.CharField(max_length=30)
    address = models.ForeignKey(Address)

forms.py

 
from django import forms
from .models import Address, Friend
from django.forms.models import inlineformset_factory

MAX_ADDRESS = 2   #updated
AddressFormSet = inlineformset_factory(Address, Friend, extra=MAX_ADDRESS)   #updated

class UserAddressForm(forms.ModelForm):
    class Meta:
        model = Address

view.py

from django.shortcuts import render_to_response
from .models import *
from .forms import UserSubmittedAddressForm, AddressFormSet

def submit(request):
    if request.POST:
        #Logic
    else:
        form = UserAddressForm()
        address_formSet = AddressFormSet(instance=Address())
    # render response

template code

      {{ form.as_table }}
      {{ address_formset.as_table }}

0👍

It’s used to work with e.g. a table of records. It’s a way to create data grid functionality in such a way that Django does all the heavy lifting (all data for all the records are sent back in the same POST).

Leave a comment