Lesson 41 of 60 – Django Forms
68%

Django Forms

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.

Note: Django Forms can handle form fields, validation, submitted data, and error messages while reducing repetitive HTML and Python code.

1. What is a Django Form?

A Django Form is a Python class used to represent and process form data.

For example, a student admission form may contain:

  • Name
  • Email
  • Mobile number
  • Course
  • Address

Django provides tools to create and validate these fields.

2. Why Use Django Forms?

Django Forms simplify the process of working with HTML forms.

  • Create form fields using Python.
  • Generate HTML form controls.
  • Validate submitted data.
  • Display validation errors.
  • Clean submitted data.
  • Handle required fields.
  • Reduce repetitive form code.

3. Importing 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.

4. Creating a Basic Form

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.

5. CharField

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.

6. EmailField

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.

7. IntegerField

IntegerField is used for integer values.

age = forms.IntegerField()

Django validates the submitted value as an integer.

8. BooleanField

BooleanField is useful for true/false values, such as accepting terms and conditions.

agree = forms.BooleanField()

It is commonly rendered as a checkbox.

9. ChoiceField

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.

10. MultipleChoiceField

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.

11. Required Fields

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
)

12. Labels

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.

13. Initial Values

The initial argument can provide an initial value.

city = forms.CharField(
    initial="Aurangabad"
)

The initial value is displayed when the form is first rendered.

14. Widgets

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.

15. Textarea Widget

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.

16. Rendering a Form in a Template

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.

17. Form HTML Structure

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>

18. CSRF Token

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.

19. GET and POST Forms

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>

20. Checking form.is_valid()

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.

21. Creating a Form in a View

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}
    )

22. cleaned_data

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.

23. Displaying Form Errors

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 }}

24. Custom Validation

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

25. Form-Level Validation

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

26. Form Initial Data from View

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.

27. Form Validation Workflow

A typical Django form workflow is:

  1. Create the form class.
  2. Display the form in a template.
  3. User enters information.
  4. User submits the form.
  5. View receives the request.
  6. Form is created with submitted data.
  7. is_valid() validates the data.
  8. Use cleaned_data after successful validation.
  9. Save or process the information.

28. Complete Django Form Example

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}
    )

29. Common Django Form Mistakes

  • Forgetting to import forms.
  • Forgetting to inherit from forms.Form.
  • Not using request.POST when processing POST data.
  • Forgetting {% csrf_token %} in POST forms.
  • Not checking form.is_valid().
  • Trying to use cleaned_data before validation.
  • Using incorrect field names.
  • Forgetting to include the form in the template context.
  • Not displaying form validation errors.

30. Django Forms Summary

Django Forms provide a structured way to create and process user input.

  • Create forms by inheriting from forms.Form.
  • Use fields such as CharField, EmailField, IntegerField, and ChoiceField.
  • Use widgets to customize HTML controls.
  • Use is_valid() to validate submitted data.
  • Use cleaned_data after successful validation.
  • Use ValidationError for custom validation errors.
  • Use csrf_token with internal POST forms.
  • Use GET for requests such as search and filtering when appropriate.
  • Use POST when submitting data that changes server-side state.
  • Django Forms reduce repetitive HTML and validation code.

📌 Key Points

  • Django Forms are created using forms.Form.
  • Form fields define the type of user input.
  • is_valid() validates submitted form data.
  • cleaned_data contains validated values.
  • Widgets control how fields are rendered in HTML.
  • csrf_token should be used with internal POST forms.
  • Custom validation can be created using clean_<fieldname>().
  • The clean() method can validate multiple fields together.
  • Form errors can be displayed to users.
  • Django Forms make form processing easier and more organized.

🧠 Quick Quiz

Question: Which method is used to check whether a Django form contains valid data?