Learn Django

Update the View

The processing payment utility created in the previous lesson will be called from the subscriber view that was already created. In this lesson you'll update this view to process the payment, and auto-login a user. Open /.../crmeasy/crmapp/subscribers/views.py and edit the code as follows.

Import Additional Utilities

There are several additional utilities that need to be imported. Add these additional imports.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
from django.shortcuts import render
from django.contrib.auth.models import User
from django.http import HttpResponseRedirect
from django.contrib.auth import authenticate, login
from django.forms.forms import NON_FIELD_ERRORS
from django.conf import settings
from django.core.urlresolvers import reverse

from .forms import SubscriberForm
from .models import Subscriber

import stripe

Code Review

Line 4: These utilities will be used to authenticate and auto-login the user.

Line 5: This will be used to append errors to the form in case Stripe reports an error. For example, if we try to process a credit card and it is declined, we need a way to communicate that to the user. This utility will help us send that error message back to the user.

Line 6: Imports the settings file which will be used to retrieve the Stripe keys.

Line 7: This is a utility that can be used to lookup a view's URL configuration.

Line 12: Imports the Stripe library.

Add the Process Payment Code

The subscriber_new() view must be updated to process the payment. Locate the # Process payment (via Stripe) comment and add this code beneath it.

This code first attempts to charge the customer. It does this using the new charge() method created on the model in the previous lesson. If that charge fails, the except statement kicks in. This statement will retrieve the error from Stripe and make sure it gets displayed in the user's browser.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
# Process payment (via Stripe)
fee = settings.SUBSCRIPTION_PRICE
try:
    stripe_customer = sub.charge(request, email, fee)
except stripe.StripeError as e:
    form._errors[NON_FIELD_ERRORS] = form.error_class([e.args[0]])
    return render(request, template,
        {'form':form,
         'STRIPE_PUBLISHABLE_KEY':settings.STRIPE_PUBLISHABLE_KEY}
    )

Code Review

Line 2: This imports the SUBSCRIPTION_PRICE value from the settings file.

Lines 3-10: This is the beginning of a try/except statement. We will try to process the user's payment on line 4. If that fails, we will take the error from Stripe and return it to the end user via the non_field_errors mechanism.

Auto-Login the User

If a user's payment is successful, we can improve their experience by automatically logging them in and returning them to the application. Locate the '# Auto login the user' comment and update the code.

This is what the code currently shows:

1
2
# Auto login the user
return HttpResponseRedirect('/success/')

Remove the return statement and change it to the following:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
# Auto login the user
a_u = authenticate(username=username, password=password)
if a_u is not None:
    if a_u.is_active:
        login(request, a_u)
        return HttpResponseRedirect(reverse('account_list'))
    else:
        return HttpResponseRedirect(
            reverse('django.contrib.auth.views.login')
        )
else:
    return HttpResponseRedirect(reverse('sub_new'))

Code Review

Line 2: This uses Django's authenticate utility to authorize the user. It takes the username and password as arguments.

Line 3-12: If the authentication is successful, then the user is logged in and returned the the account list. Otherwise they are redirected to the login or signup page.

Update the Main Return Statement

The last step is to modify view's main return statement. Locate the subscriber_new() view's very last return statement and modify it as follows.

This is what the code currently shows:

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

Modify this statement show it shows:

1
2
3
return render(request, template,
    {'form':form,
     'STRIPE_PUBLISHABLE_KEY':settings.STRIPE_PUBLISHABLE_KEY})

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 subscriber view to use processing code"

Track your progress with a free account