DEV Community

Cover image for Django Tutorial #6: Understanding Forms in Django | User Input and Form Validation
S.P.Randhawa
S.P.Randhawa

Posted on

Django Tutorial #6: Understanding Forms in Django | User Input and Form Validation

Django Tutorial #6: Understanding Forms in Django | User Input and Form Validation

Welcome back to Part 6 of my Django Tutorial Series! 🚀

So far, we have explored Django URLs, Views, Templates, Models, and Databases.

Now let's learn how websites collect information from users.

For example:

  • Registration forms
  • Login forms
  • Contact forms
  • Feedback forms
  • Student admission forms

Django Forms make it easier to collect, process, and validate user input.

In this tutorial, we will learn:

  • What are Django Forms?
  • Why do we use them?
  • How to create a Django Form.
  • How to display forms in HTML.
  • How to handle submitted data.
  • Understanding form validation.

1. What Are Django Forms?

Django Forms are Python classes used to create and process HTML forms.

They help developers collect user information and validate it before processing or storing it.

Django provides two commonly used form approaches:

  1. forms.Form – Used to create forms by defining fields manually.
  2. forms.ModelForm – Used to create forms based on an existing database model.

2. Creating Your First Django Form

First, create a file named forms.py inside your Django application.

forms.py

from django import forms

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

Explanation:

  • CharField accepts text.
  • EmailField validates email format.
  • Textarea provides a larger text input area.
  • ContactForm defines the structure of our form.

3. Displaying the Form in a View

Open views.py.

from django.shortcuts import render
from .forms import ContactForm

def contact(request):
    form = ContactForm()
    return render(
        request,
        'contact.html',
        {'form': form}
    )
Enter fullscreen mode Exit fullscreen mode

This view creates an empty form and passes it to the HTML template.

4. Creating the HTML Template

Create contact.html inside the templates folder.

<h2>Contact Us</h2>

<form method="POST">
    {% csrf_token %}
    {{ form.as_p }}

    <button type="submit">Submit</button>
</form>
Enter fullscreen mode Exit fullscreen mode

Important concepts:

  • method="POST" sends submitted form data.
  • {{ form.as_p }} displays form fields inside paragraph elements.
  • {% csrf_token %} protects POST forms against Cross-Site Request Forgery (CSRF) attacks.

5. Handling Form Submission

Now let's process the information submitted by the user.

Update views.py:

from django.shortcuts import render
from .forms import ContactForm

def contact(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']

            return render(
                request,
                'success.html',
                {'name': name}
            )
    else:
        form = ContactForm()

    return render(
        request,
        'contact.html',
        {'form': form}
    )
Enter fullscreen mode Exit fullscreen mode

Here is what happens:

  1. Django checks whether the request uses POST.
  2. Submitted data is passed to the form.
  3. is_valid() checks the entered information.
  4. cleaned_data provides validated data.
  5. A success page is displayed when validation succeeds.

6. What Is Form Validation?

Form validation means checking whether the information entered by a user is correct and follows the required rules.

For example:

  • Checking whether an email address is valid.
  • Making sure required fields are not empty.
  • Checking maximum character limits.
  • Validating input before saving it.

Django provides built-in validation for many form fields.

7. What Is ModelForm?

ModelForm is used when we want to create a form directly from an existing Django model.

Example:

from django import forms
from .models import Student

class StudentForm(forms.ModelForm):

    class Meta:
        model = Student
        fields = ['name', 'email', 'roll_number']
Enter fullscreen mode Exit fullscreen mode

This automatically creates form fields based on the selected model fields.

8. Why Are Django Forms Important?

  • They simplify user input handling.
  • They provide built-in validation.
  • They reduce repetitive code.
  • They support secure form processing.
  • They work with Django Models.
  • They help build interactive web applications.

9. Conclusion

Django Forms are an important part of web development because they make collecting and validating user information easier.

Whether you are creating a registration system, contact page, or student management application, Django Forms can simplify the process.

What's Next?

In Django Tutorial #7, we will explore CRUD Operations and learn how to Create, Read, Update, and Delete records in a database.

If you found this tutorial helpful, share your feedback in the comments!

Happy Coding! 💜

— SP Randhawa

Top comments (1)

Collapse
 
sp_randhawa profile image
S.P.Randhawa •

✨ Welcome to Part 6 of my Django Tutorial Series!

In this article, we learned about Django Forms, user input, form validation, and ModelForms.

Forms are an essential part of web applications because they help us collect and validate user information.

💡 Have you ever created a registration form or contact form using Django?

Let me know your experience!

Happy Coding! 💜