Learn Django

Create the Subscriber Form

The subscriber form will eventually become the one seen on the demo site. In this chapter your focus is building the first part of the form. Specifically, the form created in this chapter will only have the username, password, and email address fields. The following two chapters will show you how to build the rest of the signup form.

The directions below will show you how to create the form and explain how it works.

Step 1: Create the Forms File

Form definitions belong in the forms.py file inside the relevant app folder. Follow these steps to create the file.

  1. Navigate to /.../crmeasy/crmapp/subscribers
  2. Create a file there named forms.py
  3. Open this file in your IDE

Step 2: Create the SubscriberForm Class

Type in the following code into forms.py.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
from django import forms
from django.contrib.auth.forms import UserCreationForm

class SubscriberForm(UserCreationForm):
    email = forms.EmailField(
        required=True, widget=forms.TextInput(attrs={'class':'form-control'})
    )
    username = forms.CharField(
        widget=forms.TextInput(attrs={'class':'form-control'})
    )
    password1 = forms.CharField(
        widget=forms.TextInput(attrs={'class':'form-control', 'type':'password'})
    )
    password2 = forms.CharField(
        widget=forms.TextInput(attrs={'class':'form-control', 'type':'password'})
    )

Code Review

Line 1: The first step is to import Django's UserCreationForm class. This is a form that is pre-built and comes with all of the validation required to create a new user.

Line 4: This is how a custom form class is defined. It's a Python class that subclasses UserCreationForm.

Lines 5-16: These lines of code are defining the fields of the form. At this point the form will have a first_name, last_name, email, username, and two password fields. As we're subclassing the Django form, defining fields like this is not required unless you want to change some aspect of them. Here we're adding the class attribute to the HTML elements. When these form fields are rendered in HTML the class attribute will be class='form-control'.

Step 3: Commit Changes

Execute these commands to commit your changes in Git.

1
2
3
4
5
# add files
(venv)$ git add .

# commit files
(venv)$ git commit -m "created the subscriber form"

Track your progress with a free account