Working with Forms in Django: Collecting User Input Made Easy

Forms are essential for any web application that interacts with users — whether for login, registration, surveys, or data entry. Django’s built-in form system makes handling forms straightforward and secure.

Let’s explore how to create and use forms in Django!


️ What Is a Django Form?

A form in Django is a class that describes the fields you want to display to users and validates the submitted data.


Creating a Simple Form

You can define a form in forms.py inside your app folder:

python
from django import forms

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


️ Displaying the Form in a Template

In your view, instantiate the form and send it to the template:

python
from django.shortcuts import render
from .forms import ContactForm

def contact_view(request):
form = ContactForm()
return render(request, 'contact.html', {'form': form})

In contact.html:

html
<form method="post">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Send</button>
</form>

{{ form.as_p }} renders all form fields wrapped in <p> tags.


Handling Form Submission

To process submitted data, update your view:

python
def contact_view(request):
if request.method == 'POST':
form = ContactForm(request.POST)
if form.is_valid():
name = form.cleaned_data['name']
email = form.cleaned_data['email']
message = form.cleaned_data['message']
# Process the data (e.g., save or send email)
return render(request, 'thanks.html', {'name': name})
else:
form = ContactForm()
return render(request, 'contact.html', {'form': form})
  • form.is_valid() checks if submitted data passes validation.

  • Valid data is accessible via form.cleaned_data.


️ CSRF Protection

Always include {% csrf_token %} inside your form to protect against cross-site request forgery attacks.


Model Forms: Forms Tied to Models

For forms that create or update database records, Django provides ModelForms:

python
from django.forms import ModelForm
from .models import Book

class BookForm(ModelForm):
class Meta:
model = Book
fields = ['title', 'author', 'published_year']

This auto-generates form fields based on the model.


Summary

Step Code Example
Define a form class ContactForm(forms.Form): ...
Display form {{ form.as_p }} in template
Process submission if form.is_valid(): ... in view
Use ModelForm class BookForm(ModelForm): ...

Leave a Reply

Your email address will not be published. Required fields are marked *