Django Forms provide a convenient way to create, display, validate, and process HTML forms in Django applications.
Forms are commonly used for registration, login, contact forms, student admission, feedback, search, and data entry systems.
A Django Form is a Python class used to represent and process form data.
For example, a student admission form may contain:
Django provides tools to create and validate these fields.
Django Forms simplify the process of working with HTML forms.
Django's forms functionality is available through the
django.forms module.
from django import forms
This import allows you to create form classes and form fields.
Create a Python class that inherits from forms.Form.
from django import forms
class StudentForm(forms.Form):
name = forms.CharField(
max_length=100
)
email = forms.EmailField()
This form contains Name and Email fields.
CharField is commonly used for text input.
name = forms.CharField(
max_length=100
)
It can be used for names, titles, usernames, and other short text values.
EmailField is used for email addresses and provides email
validation.
email = forms.EmailField()
Django can validate whether the submitted value has a valid email format.
IntegerField is used for integer values.
age = forms.IntegerField()
Django validates the submitted value as an integer.
BooleanField is useful for true/false values, such as accepting
terms and conditions.
agree = forms.BooleanField()
It is commonly rendered as a checkbox.
ChoiceField allows the user to select one value from a list of
choices.
course = forms.ChoiceField(
choices=[
("python", "Python"),
("java", "Java"),
("django", "Django")
]
)
The first value is stored as the choice value and the second is displayed to the user.
MultipleChoiceField allows users to select multiple choices.
skills = forms.MultipleChoiceField(
choices=[
("html", "HTML"),
("css", "CSS"),
("python", "Python")
]
)
It can be used when multiple values are allowed.
Django form fields are generally required by default.
name = forms.CharField(
required=True
)
If the user submits an empty value, Django can generate a validation error.
To make a field optional:
phone = forms.CharField(
required=False
)
The label argument controls the text displayed with a form
field.
name = forms.CharField(
label="Student Name"
)
Labels make forms easier for users to understand.
The initial argument can provide an initial value.
city = forms.CharField(
initial="Aurangabad"
)
The initial value is displayed when the form is first rendered.
Widgets control how form fields are represented in HTML.
name = forms.CharField(
widget=forms.TextInput(
attrs={
"class": "form-control"
}
)
)
Widgets can be customized using HTML attributes.
Use Textarea when you want a multi-line text input.
address = forms.CharField(
widget=forms.Textarea(
attrs={
"rows": 4
}
)
)
This is useful for addresses, descriptions, messages, and comments.
A form can be passed from a view to a template.
return render(
request,
"student_form.html",
{"form": form}
)
The template can render the form using:
{{ form.as_p }}
This renders the form fields inside paragraph elements.
A basic HTML form can contain the Django form and a submit button.
<form method="post">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">
Submit
</button>
</form>
Django provides CSRF protection for POST forms.
{% csrf_token %}
The CSRF token should normally be included inside internal POST forms. It helps protect against cross-site request forgery.
Forms can commonly use GET or POST requests.
GET is often useful for search and filtering:
<form method="get">
...
</form>
POST is commonly used when submitting data that changes or creates data:
<form method="post">
{% csrf_token %}
...
</form>
After receiving submitted data, use is_valid() to validate the
form.
if form.is_valid():
print("Valid form")
If validation succeeds, cleaned data becomes available through
cleaned_data.
A basic view can create and process a form:
from django.shortcuts import render
from .forms import StudentForm
def student_form(request):
if request.method == "POST":
form = StudentForm(
request.POST
)
if form.is_valid():
print(
form.cleaned_data
)
else:
form = StudentForm()
return render(
request,
"student_form.html",
{"form": form}
)
After successful validation, Django stores validated values in
cleaned_data.
if form.is_valid():
name = form.cleaned_data[
"name"
]
email = form.cleaned_data[
"email"
]
The values can then be used in application logic.
If validation fails, Django stores error information in the form.
if not form.is_valid():
print(form.errors)
When using standard form rendering, errors can also be displayed in the template.
{{ form.as_p }}
You can create custom validation by defining a clean_ method
for a specific field.
class StudentForm(forms.Form):
name = forms.CharField(
max_length=100
)
def clean_name(self):
name = self.cleaned_data[
"name"
]
if len(name) < 3:
raise forms.ValidationError(
"Name must contain at least 3 characters."
)
return name
The clean() method can be used when validation depends on
multiple fields.
class StudentForm(forms.Form):
email = forms.EmailField()
confirm_email = forms.EmailField()
def clean(self):
cleaned_data = super().clean()
email = cleaned_data.get(
"email"
)
confirm = cleaned_data.get(
"confirm_email"
)
if email and confirm:
if email != confirm:
raise forms.ValidationError(
"Emails do not match."
)
return cleaned_data
Initial values can also be supplied when creating a form.
form = StudentForm(
initial={
"name": "Rahul",
"email": "rahul@example.com"
}
)
This is useful when displaying existing or suggested values.
A typical Django form workflow is:
is_valid() validates the data.cleaned_data after successful validation.forms.py
from django import forms
class StudentForm(forms.Form):
name = forms.CharField(
max_length=100,
label="Student Name"
)
email = forms.EmailField()
age = forms.IntegerField()
course = forms.ChoiceField(
choices=[
("python", "Python"),
("django", "Django"),
("java", "Java")
]
)
views.py
from django.shortcuts import render
from .forms import StudentForm
def student_form(request):
if request.method == "POST":
form = StudentForm(
request.POST
)
if form.is_valid():
name = form.cleaned_data[
"name"
]
print(name)
else:
form = StudentForm()
return render(
request,
"student_form.html",
{"form": form}
)
forms.forms.Form.request.POST when processing POST data.{% csrf_token %} in POST forms.form.is_valid().cleaned_data before validation.Django Forms provide a structured way to create and process user input.
forms.Form.is_valid() to validate submitted data.cleaned_data after successful validation.ValidationError for custom validation errors.csrf_token with internal POST forms.forms.Form.is_valid() validates submitted form data.cleaned_data contains validated values.csrf_token should be used with internal POST forms.clean_<fieldname>().clean() method can validate multiple fields together.Question: Which method is used to check whether a Django form contains valid data?