Advanced Forms
- Advanced Django form techniques including Formsets, widgets, and dynamic form behavior.k
What is a Formset?
A Formset is a collection of multiple forms of the same type displayed and processed together.
Used when:
Adding multiple records at once
Repeating the same form fields
Dynamic form handling
Real-World Example
Add multiple students at once
Upload multiple documents
Enter multiple phone numbers
Simple Form Class for Formset
This form will be repeated inside a formset.
from django import forms
class StudentForm(forms.Form):
name = forms.CharField(max_length=100)
age = forms.IntegerField()
Creating a Formset
Creates a formset with multiple StudentForm forms.
from django.forms import formset_factory
from .forms import StudentForm
StudentFormSet = formset_factory(StudentForm, extra=3)
extra=3 → number of empty forms shown.
Using Formset in View [views.py]
Handles multiple form submissions together.
def student_formset_view(request):
StudentSet = StudentFormSet(request.POST or None)
if request.method == 'POST' and StudentSet.is_valid():
for form in StudentSet:
print(form.cleaned_data)
return render(request, 'student_formset.html', {'formset': StudentSet})
Rendering Formset in Template
student_formset.html
<form method="post">
{% csrf_token %}
{{ formset.management_form }}
{% for form in formset %}
{{ form.as_p }}
{% endfor %}
<button type="submit">Submit</button>
</form>
management_form is mandatory.
Model Formsets
from django.forms import modelformset_factory
from .models import Student
StudentModelFormSet = modelformset_factory(
Student,
fields=('name', 'age'),
extra=2
)
What is File Upload?
Django allows users to upload files (images, PDFs, documents) using forms.
Step 1: Media Configuration
Media Settings Configuration
settings.py
MEDIA_URL = '/media/'
MEDIA_ROOT = BASE_DIR / 'media'
urls.py
from django.conf import settings
from django.conf.urls.static import static
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Step 2: Model with FileField
Model with File Upload
class Document(models.Model):
title = models.CharField(max_length=100)
file = models.FileField(upload_to='documents/')
Step 3: Create ModelForm for File Upload
File Upload ModelForm
class DocumentForm(forms.ModelForm):
class Meta:
model = Document
fields = ['title', 'file']
- Step 4: View for File Upload
Handle File Upload in View
def upload_file(request):
form = DocumentForm(request.POST or None, request.FILES or None)
if form.is_valid():
form.save()
return render(request, 'upload.html', {'form': form})
request.FILES is required.
Step 5: Template for File Upload
File Upload Template
<form method="post" enctype="multipart/form-data">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Upload</button>
</form>
enctype is mandatory.
File Validation (Size & Type)
File Size Validation
def clean_file(self):
file = self.cleaned_data.get('file')
if file.size > 2 * 1024 * 1024:
raise forms.ValidationError("File size must be under 2MB")
return file