Learn Django

Understanding Forms

Forms are a big part of the internet. They're one of the primary ways that users submit data to servers when using a web browser like Chrome or IE. Given their importance, Django comes with an extensive form creation and management library. At a high level, this library makes it easy to design forms and how they will look on a web page. In addition, it can help process forms after a user fills one out and submits it to the server. Here are a few of the features provided by the form library:

  • Generate the HTML to display a form on a web page
  • Provide validation for submitted form data
  • Provide error message responses in case the user data is invalid
  • Make it easy to work with form data in views e.g. save it to a database

Below is a short introduction to how forms work.

Defining Forms

Forms are created within an app's directory in a file named forms.py. This file isn't created by default - it has to be manually created. Once created, forms are defined by creating Python classes and subclassing Django's forms class. Here's an example form.

1
2
3
from django import forms

class ContactForm(forms.ModelForm):

Defining Form Fields

The purpose of a form is to give users a chance to enter data and submit it to a server. To gather data a form needs fields. In Django, form fields are created as attributes of the class. The attributes are classed from Django's Form fields. Here's how form fields are defined:

1
2
3
4
from django import forms

class SearchForm(forms.ModelForm):
    search_query = forms.CharField(max_length=100)

In the above example, line 4 defines the first form field. This is an attribute of the ContactForm class. The field's name is search_query, and it is being created from Django's available form fields - in this case the CharField() field.

Displaying Forms

Once a form has been designed it can then be displayed to users on a web page. Two things need to happen to be able to do this. First, a view must be created that passes the form object to a template. Second, a template must be configured to display the form.

Here's what a form view might look like. On line 7 the form object is created from the SearchForm() class. The form is then rendered with the search.html template on line 9.

1
2
3
4
5
6
7
8
9
from django.shortcuts import render

def search(request):
    if request.method == 'POST':
        # do some processing
    else:
        form = SearchForm()

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

Processing Forms

Once a form has been designed and configured to display on a web page, the code to process the form can be created. There are many different things you can do with form data. The example here is a search form, which could be used to search a database.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
from django.shortcuts import render

def search(request):
    if request.method == 'POST':
        form = ContactForm(request.POST)
        if form.is_valid():
            s_query = form.cleaned_data['search_query']
            s_results = SomeTable.objects.filter(name=s_query)
            return render(request, 'search.html', {'form': form, 's_results': s_results})
    else:
        form = SearchForm()

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

The form processing code above will check to see if this is a HTTP POST (line 4) - a POST would indicate that a user is submitting the form. If it is a POST, then the form object will be created from the user's submitted data, which can be found in request.POST (line 5).

The is_valid() method (line 6) can be called on each form object. This method will check to see if the data the user submitted is valid compared to the original form design. For example, if the form design specifies a date field, and the user submitted plain text in that field, the is_valid() check would catch it and display an error message to the user. If the form is valid the form fields will be available in the cleaned_data dictionary.

The s_query object is assigned a value by access the search_query field in the form.cleaned_data dictionary (line 7). Once the user's query is known, the database can then be queried (line 8) to obtain the search results. Once the results are known, the result set can be returned the the template file to display to the end user (line 9).

With the introduction to Django Forms complete, it's now time to build the Subscriber form. Here are the instructions to do so.

Track your progress with a free account