Learn Django

Create the Subscriber View

The next step in the process is to create the view that renders, and then processes the form. This view will be function-based (FBV). The flow of the code is simple. If a user requests a blank subscription form, render a blank form. If the user is submitting a form that has been filled out, process the form by first performing validation on it, and if that passes, save the record to the database.

To create the view, open the /.../crmeasy/subscribers/views.py file. Type in the following code.

from django.shortcuts import render
from django.contrib.auth.models import User
from django.http import HttpResponseRedirect

from .forms import SubscriberForm

def subscriber_new(request, template='subscribers/subscriber_new.html'):
    if request.method == 'POST':
        form = SubscriberForm(request.POST)
        if form.is_valid():
            # Unpack form values
            username = form.cleaned_data['username']
            password = form.cleaned_data['password1']
            email = form.cleaned_data['email']
            # Create the User record
            user = User(username=username, email=email)
            # Create Subscriber Record
            # Process payment (via Stripe)
            # Auto login the user
            return HttpResponseRedirect('/success/')
        form = SubscriberForm()

    return render(request, template, {'form':form})

Code Review

Line 1: This imports the render utility, which takes a template and context dictionary and returns a web response object. It's a shortcut that makes it easy to return the proper content after the view is done processing.

Line 2: This imports the User model which will be used later in the view to create the user record.

Line 3: This imports the HttpReseponseRedirect utility. This utility can be used to redirect users to any URL.

Line 5: This imports the SubscriberForm that was created in the previous lesson.

Line 7: This defines the view function that will be used to process requests made to the /signup/ URL. These functions must take in the request object at the very least. Our application defines another object that this function can take; template. If we wanted to use this function to process forms in different templates, we could easily do so by passing in a different template name.

Line 8: This checks the request to see what kind of HTTP method is being used. When a blank form is rendered, it is a GET request. When a user submits the form for processing, it will be a POST request.

Line 9: This creates a form object. That's done by passing in request.POST to the SubscriberForm class. Whenever a form is submitted, it's data (i.e. its HTML inputs) can be accessed at request.POST.

Line 10: Every form object will have a is_valid() method. Running this method will validate the user's input to see if it matches what we expect. At this point, the SubscriberForm validation will check to see if the two passwords match, if the username is not too long and contains only valid characters, and if the email is in the right format. If the validation passes, then the processing can continue.

Lines 12-14: These lines create objects from the user inputted data. These objects will be used to create the actual user record a little later. Note that the user inputted data is accessed in the form.cleaned_data['field_name'] format.

Line 16: This will create a non-persisted instance of the user record.

Line 17: This will set the password on the user record.

Line 18: This will save the user record to the database.

Line 22: If all of this succeeds, then the user will be redirected to /success/. This is just a temporary setting.

Lines 23-24: This code is executed if the user is requesting the subscription form for the first time. If that's the case, this code kicks in and will create an instance of the SubscriberForm. This instance can then be displayed in the template.

Line 26: This uses the render shortcut to return the request, template, and form to the user. This marks the end of the view processing and is what provides the blank form to the end user.

Commit Changes

Execute these commands to commit your changes in Git.

# add files
(venv)$ git add .

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

Track your progress with a free account