Subjects

All subjects Django Java Python React Spring Boot JavaScript PHP
Sign Up Free
Interview question

What are Django Forms and how do you handle form validation and processing? Django Forms क्या हैं? Form validation और processing कैसे करते हैं?

Answer

Django Forms provide form handling, validation, and rendering. Use ModelForm to automatically generate forms from models. Forms handle data validation, CSRF protection, and error messages without writing additional code.

// forms.py
from django import forms
from .models import Product, Review

// Model Form - Auto-generated from Model
class ProductForm(forms.ModelForm):
    # Override field properties
    description = forms.CharField(
        widget=forms.Textarea(attrs={
            'rows': 5,
            'placeholder': 'Enter product description'
        }),
        required=True,
        help_text='Minimum 50 characters required'
    )
    
    price = forms.DecimalField(
        max_digits=10,
        decimal_places=2,
        min_value=0.01,
        error_messages={
            'invalid': 'Enter a valid price',
            'min_value': 'Price must be greater than 0'
        }
    )
    
    class Meta:
        model = Product
        fields = ['name', 'description', 'price', 'category', 'quantity']
        labels = {
            'name': 'Product Name',
            'price': 'Product Price (USD)'
        }
        widgets = {
            'name': forms.TextInput(attrs={'class': 'form-control'}),
            'category': forms.Select(attrs={'class': 'form-control'}),
            'quantity': forms.NumberInput(attrs={'class': 'form-control', 'min': 0}),
        }
    
    # Custom validation for single field
    def clean_name(self):
        name = self.cleaned_data.get('name')
        if len(name) < 3:
            raise forms.ValidationError('Name must be at least 3 characters')
        return name
    
    # Custom validation across fields
    def clean(self):
        cleaned_data = super().clean()
        price = cleaned_data.get('price')
        quantity = cleaned_data.get('quantity')
        
        if price and quantity:
            if quantity == 0 and price > 0:
                raise forms.ValidationError(
                    'Cannot set price for out-of-stock product'
                )
        return cleaned_data

// Regular Form - Manual field definition
class ReviewForm(forms.Form):
    RATING_CHOICES = [(i, str(i)) for i in range(1, 6)]
    
    rating = forms.ChoiceField(
        choices=RATING_CHOICES,
        widget=forms.RadioSelect,
        required=True
    )
    
    title = forms.CharField(
        max_length=200,
        widget=forms.TextInput(attrs={'class': 'form-control'})
    )
    
    review = forms.CharField(
        widget=forms.Textarea(attrs={
            'class': 'form-control',
            'rows': 5
        })
    )
    
    def clean_review(self):
        review = self.cleaned_data.get('review')
        if len(review) < 10:
            raise forms.ValidationError('Review must be at least 10 characters')
        return review

// Using Forms in Views
from django.shortcuts import render, redirect

def create_product(request):
    if request.method == 'POST':
        form = ProductForm(request.POST, request.FILES)  # request.FILES for file uploads
        if form.is_valid():  # Runs all validations
            product = form.save(commit=False)
            product.created_by = request.user
            product.save()
            return redirect('product_detail', pk=product.id)
        # If not valid, form re-rendered with errors
    else:
        form = ProductForm()
    
    return render(request, 'products/form.html', {'form': form})

// Templates
<form method='post' enctype='multipart/form-data'>
    {% csrf_token %}
    
    <!-- Render entire form -->
    {{ form.as_p }}  <!-- Paragraphs -->
    {{ form.as_table }}  <!-- Table -->
    {{ form.as_ul }}  <!-- List -->
    
    <!-- Or render fields individually -->
    <div class='form-group'>
        {{ form.name.label_tag }}
        {{ form.name }}
        {% if form.name.errors %}
            <div class='error'>
                {{ form.name.errors }}
            </div>
        {% endif %}
    </div>
    
    <button type='submit'>Submit</button>
</form>

// Form Validation Flow
// 1. form.is_valid() called
// 2. Run field-level clean_<field>()
// 3. Run form-level clean()
// 4. Populate cleaned_data
// 5. Return True/False

// Common Validations
min_length, max_length
min_value, max_value
regex pattern
required
unique
Email validator
URL validator
Custom validators
Django Forms:

ModelForm - Model से auto-generate:
class ProductForm(forms.ModelForm):
    class Meta:
        model = Product
        fields = ['name', 'price']

Regular Form - Manual fields:
class ReviewForm(forms.Form):
    rating = forms.ChoiceField()
    review = forms.CharField()

Validation:
1. clean_<field>() - Single field
2. clean() - Multiple fields
3. Validators - Custom functions

Form Usage in Views:
1. GET: Blank form render करो
2. POST: Form data process करो
3. is_valid(): Validation करो
4. cleaned_data: Validated data
5. save(): Database में save

Template में:
{{ form }}
{{ form.field }}
{{ form.field.errors }}
{% csrf_token %}

Benefits:
- CSRF protection
- Input validation
- Error messages
- HTML generation
- Security by default

Was this answer clear?