Forms and Validations
Handling user input securely with Django Forms, ModelForms, and CSRF protection.
🧑🏫 Sabse pehle — simple mein samjho#
HTML mein form bana kar data submit karna aasan hai, par backend pe ye check karna ki email valid hai ya password 8 characters ka hai, bada sar dard hai. Django Forms tumhara ye saara kaam kar deta hai. Wo tumhare liye safe HTML generate karta hai, aur data aane par usko automatically validate karta hai. Aur agar tumhara form exactly database model jaisa hi hai (jaise "Create Post"), toh tum ModelForm use kar sakte ho jo seedha database mein save bhi kar dega!
1. Standard Django Forms#
You define a form class exactly like you define a database model.
forms.py
from django import forms
class ContactForm(forms.Form):
name = forms.CharField(max_length=100)
email = forms.EmailField()
message = forms.CharField(widget=forms.Textarea)
views.py
from django.shortcuts import render, redirect
from .forms import ContactForm
def contact(request):
if request.method == 'POST':
# Populate the form with the data the user submitted
form = ContactForm(request.POST)
# Django automatically checks if the email is valid, name isn't too long, etc.
if form.is_valid():
# Extract the cleaned (safe) dictionary of data
name = form.cleaned_data.get('name')
# ... send email ...
return redirect('success-page')
else:
# If it's a GET request, just display a blank form
form = ContactForm()
return render(request, 'contact.html', {'form': form})
2. Rendering Forms in Templates and CSRF#
You pass the form object to your template and Django renders the HTML inputs for you.
Crucial Security Measure: Every POST form in Django MUST include the {% csrf_token %} tag. This generates a hidden input with a secret token to prevent Cross-Site Request Forgery attacks (hackers submitting forms on behalf of your users from a different website). Without it, Django will block the submission with a 403 Forbidden error!
contact.html
<form method="POST">
<!-- Mandatory for security! -->
{% csrf_token %}
<!-- Render the form fields as paragraph tags -->
{{ form.as_p }}
<button type="submit">Send Message</button>
</form>
3. ModelForms (The Shortcut)#
Most of the time, your forms directly map to your database models (e.g., creating a new Blog Post). Writing a Model class and then writing the exact same fields in a Form class violates the DRY (Don't Repeat Yourself) principle.
ModelForm reads your model and automatically creates the corresponding form fields!
models.py
class Post(models.Model):
title = models.CharField(max_length=100)
content = models.TextField()
forms.py
from django import forms
from .models import Post
class PostForm(forms.ModelForm):
class Meta:
model = Post
fields = ['title', 'content'] # Specify which fields the user is allowed to edit
views.py
def create_post(request):
if request.method == 'POST':
form = PostForm(request.POST)
if form.is_valid():
# Because it's a ModelForm, it can save directly to the database!
form.save()
return redirect('home')
else:
form = PostForm()
return render(request, 'create_post.html', {'form': form})