Creating and Validating Forms in Django

Tutorial 1 of 5

1. Introduction

In this tutorial, our main goal is to help you understand how to create and validate forms in Django using Django's Forms API. By the end of this tutorial, you will have a solid understanding of how to create forms, validate user input, and handle form submissions effectively.

What you will learn:

  • How to create forms in Django
  • Form validation
  • Handling form submissions

Prerequisites:

  • Basic knowledge of Python and Django
  • Basic understanding of HTML

2. Step-by-Step Guide

Creating a Form in Django

Django provides a powerful form library that handles rendering form HTML, validating user input, and converting those inputs into Python types.

A Django form is created by subclassing the forms.Form class. Each attribute of the form class represents a field of the form.

Form Validation

Django form provides a is_valid() method to perform form validation. This method checks if all the form fields have valid data.

Handling Form Submissions

When a form is submitted, Django will handle the form submission in a view. The form data will be validated and if the form is valid, the data will be processed.

3. Code Examples

Creating a Simple Form

from django import forms

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

In the above code, name, email, and message are the fields of the form.

Validating and Handling Form Submission

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, send email, save to database, etc
            return HttpResponseRedirect('/thanks/') # Redirect after successful handling

    else:
        form = ContactForm() # An empty form

    return render(request, 'contact.html', {'form': form})

In this view, we first check if the request method is 'POST'. If it is, that means the form has been submitted. We then validate the form data with form.is_valid(). If the form is valid, we can access the cleaned data and process it.

4. Summary

In this tutorial, we learned how to create forms in Django, validate form data, and handle form submissions.

Next steps for learning:

  • Learn about Django ModelForms
  • Learn about custom form validation

Additional resources:

5. Practice Exercises

Exercise 1: Create a Django form with the fields first_name, last_name, email, phone_number, and address.

Exercise 2: Create a view to handle the form submission, validate the form data, and print the cleaned data to the console.

Exercise 3: Create a custom validation for the phone_number field that checks if the phone number is valid.

Tips for further practice:

  • Try creating different types of forms with various fields
  • Practice validating form data with custom validation methods
  • Experiment with handling form submissions in different ways