Django Forms

Building interactive web forms with Django

📝 What are Django Forms?

Django Forms help you create, validate, and process user input easily. They handle HTML form generation, data validation, and security automatically, making form handling simple and secure.


# forms.py - Simple contact form
from django import forms

class ContactForm(forms.Form):
    name = forms.CharField(max_length=100)
    email = forms.EmailField()
    message = forms.CharField(widget=forms.Textarea)
                                    

Form Field Types

✏️

CharField

Text input fields

name = forms.CharField(max_length=50)
📧

EmailField

Email validation

email = forms.EmailField()
🔢

IntegerField

Number inputs

age = forms.IntegerField()
☑️

BooleanField

Checkboxes

agree = forms.BooleanField()

🔹 Creating a Basic Form

Forms are defined in forms.py and contain field definitions. Each field type validates specific data formats and renders appropriate HTML inputs automatically.

# forms.py
from django import forms

class FeedbackForm(forms.Form):
    name = forms.CharField(
        max_length=100,
        label='Your Name',
        required=True
    )
    email = forms.EmailField(label='Email Address')
    rating = forms.IntegerField(
        min_value=1,
        max_value=5,
        label='Rating (1-5)'
    )
    comments = forms.CharField(
        widget=forms.Textarea,
        required=False
    )

🔹 Using Forms in Views

Views handle form display and submission. Use GET requests to show empty forms and POST requests to process submitted data with validation.

# views.py
from django.shortcuts import render
from .forms import FeedbackForm

def feedback_view(request):
    if request.method == 'POST':
        form = FeedbackForm(request.POST)
        if form.is_valid():
            # Process the data
            name = form.cleaned_data['name']
            email = form.cleaned_data['email']
            # Save or send email...
            return render(request, 'success.html')
    else:
        form = FeedbackForm()
    
    return render(request, 'feedback.html', {'form': form})

🔹 Rendering Forms in Templates

Django provides multiple ways to render forms in templates. Use form.as_p for quick rendering or customize each field for complete control over appearance.

<!-- feedback.html -->
<form method="post">
    {% csrf_token %}
    
    <!-- Quick render -->
    {{ form.as_p }}
    
    <!-- OR Manual render -->
    <div>
        {{ form.name.label_tag }}
        {{ form.name }}
        {{ form.name.errors }}
    </div>
    
    <button type="submit">Submit</button>
</form>

Output:



🔹 Form Widgets

Widgets control how form fields appear in HTML. Customize input types, add CSS classes, and modify attributes to match your design requirements.

# forms.py
from django import forms

class StyledForm(forms.Form):
    name = forms.CharField(
        widget=forms.TextInput(attrs={
            'class': 'form-control',
            'placeholder': 'Enter your name'
        })
    )
    bio = forms.CharField(
        widget=forms.Textarea(attrs={
            'rows': 4,
            'cols': 50
        })
    )
    birth_date = forms.DateField(
        widget=forms.DateInput(attrs={
            'type': 'date'
        })
    )

🧠 Test Your Knowledge

What method validates form data in Django?