Learn Django

Update the View

With the form classes updated it's time to update the view so that it can process the new form values correctly. If you recall, we updated the form to include a first name and last name, in addition to address data. The view must now extract this data from the form and save it to the subscriber model that was built earlier in this chapter.

Open the file /.../crmeasy/crmapp/subscribers/views.py in your IDE. Update the view to look like the below. New or modified lines are highlighted in yellow.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
from django.shortcuts import render
from django.contrib.auth.models import User
from django.http import HttpResponseRedirect

from .forms import SubscriberForm
from .models import Subscriber

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']
            first_name = form.cleaned_data['first_name']
            last_name = form.cleaned_data['last_name']
            # Create the User record
            user = User(username=username, email=email,
                        first_name=first_name, last_name=last_name)
            user.set_password(password)
            user.save()
            # Create Subscriber Record
            address_one = form.cleaned_data['address_one']
            address_two = form.cleaned_data['address_two']
            city = form.cleaned_data['city']
            state = form.cleaned_data['state']
            sub = Subscriber(address_one=address_one, address_two=address_two,
                             city=city, state=state, user_rec=user)
            sub.save()
            # Process payment (via Stripe)
            # Auto login the user
            return HttpResponseRedirect('/success/')

    else:
        form = SubscriberForm()

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

Code Review (Only calling out code that was added or updated)

Line 6: This imports the Subscriber model. This is required so that we can save address data to the database.

Line 16-17: These lines unpack the first and last name from the form data.

Line 19-20: These lines was updated to add the first and last name when creating a user record.

Line 24-30: These lines save the address data from the form to the subscriber model.

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 "updated the view"

Track your progress with a free account