Our First Django Form

Introduction to forms

Forms are a way to collect data from our website visitors or our users. Basically, we want to collect that data, and we want to do something with it. Primarily, we grab data from the user and store that data in our database.

NOTE: Forms themselves aren’t Django specific. They are made in HTML and are found in most web applications. We assume that you already know how forms work in HTML. Therefore, this chapter will focus only on how forms work in Django.

Django’s role in forms

Handling forms can be a bit complicated. We usually have to decide which data we need from the user, and then how to display it in a form. Then, the form is rendered as HTML. The client fills out the values, and data is returned to the server after the validation. This data can be stored or used for further tasks. Django’s form service simplifies and automates much of this process. Additionally, Django provides a very secure way to deal with forms.

Now, let’s see the steps involved in making our first Django form.

NOTE: For this example, we will create a search field using Django forms.

Step 1: Make a forms.py file

We begin by creating all of our forms in a separate file called the forms.py file. This forms.py file will go inside our application’s folder.

Step 2: Import forms from Django

Now in the forms.py file, we need to import forms from Django. In order to do this, we will write the following line:

from django import forms

This line imports a very basic library for forms that we can build on top of.

Step 3: Define a class

In this step, we will define a class and create a search field. In order to do this, we add the following lines:

class SearchForm(forms.Form):
    q = forms.CharField()

In the snippet above, the SearchForm class is inheriting from the Django Form class, and q is the name of our search field, which is a type of CharField. We already have some familiarity with fields from the Models chapter.

And that’s it. Those are the basics of a form. Right now, we have the following forms.py file:

Get hands-on with 1400+ tech skills courses.