Category Archives: Sample Code

What is a Mixin?

Published / by chris / Leave a Comment

You hear a lot about “mixins”, but what exactly is a mixin? And, how can you create your own?

A Mixin is a special kind of inheritance in Python (and other object-oriented languages) and it’s starting to get a big rise in Django / Web Application Development. You can use a Mixin to allow classes in Python to share methods between any class that inherits from that Mixin. So what does it look like?

from django.http import JsonResponse

class JSONResponseMixin(object):
    A mixin that can be used to render a JSON response.
    def render_to_json_response(self, context, **response_kwargs):
        Returns a JSON response, transforming 'context' to make the payload.
        return JsonResponse(

    def get_data(self, context):
        Returns an object that will be serialized as JSON by json.dumps().
        # Note: This is *EXTREMELY* naive; in reality, you'll need
        # to do much more complex handling to ensure that arbitrary
        # objects -- such as Django model instances or querysets
        # -- can be serialized as JSON.
        return context

This is an example from the Mixin Documentation on []. As you can see just looking at this example, it’s just a plain Python class.

Now, you can pass it in to a class and call the methods just as you would if the method was on the class as self.render_to_response(...).

from django.views.generic import TemplateView

class JSONView(JSONResponseMixin, TemplateView):
    def render_to_response(self, context, **response_kwargs):
        return self.render_to_json_response(context, **response_kwargs)

This is useful if you have some code that you want to reuse among different classes in your code.

Can you think of a function that you would need to reuse in your code? Try this out! Create a Mixin and pass it into all the places that need some reusable code snippets!

How to Implement OAuth2 using Django REST Framework

Published / by chris / Leave a Comment

Let’s paint a picture for you. You want to create a web and mobile application that allows your users to login more securely than Token Authentication. You know it’s possible, but you’re not sure how to implement something like this.

We can also use Facebook, Google, Twitter, Github, etc. to authenticate users. However, I’m just going to describe how to use OAuth to authenticate with JUST our application.

Maybe there is a package you can use? You’d be correct. There is a package you can use. OAuth Authentication implementation from scratch is complicated. Therefore, I recommend NOT re-inventing the wheel. I recommend using a package that already implements it. (I’ll write a post about how OAuth can be implemented yourself, if you’re interested in learning how this works).

I’m just going to pick a random OAuth package because it really doesn’t matter. The implementation of OAuth is the same no matter which package you choose. In this case, I’m going to use django-rest-framework-social-oauth2.

Implementing OAuth2 using Django-REST-Framework-Social-OAuth2

Let’s start by installing the package.

$ pip install django-rest-framework-social-oauth2

Now, let’s add the package apps to our INSTALLED_APPS.


Next, let’s include the URLs to our

urlpatterns = patterns(
    # ...
    url(r'^auth/', include('rest_framework_social_oauth2.urls')),

Now, we need to set up the packages CONTEXT_PROCESSORS. If you are using Django 1.8+ you’ll add the CONTEXT_PROCESSORS in the TEMPLATES setting.

        # ...
        'OPTIONS': {
            'context_processors': [
                # ...

However, if you are using anything BEFORE Django 1.8, you’ll need to add the context processors like so…

    # ...

Now, we need some Authentication Backends so that Django and REST knows how to authenticate users. So, let’s add the backends to both settings.

    # ...
        # ...

    # ...

Set up Web Application

We have successfully setup our application to use OAuth2 in our Web Application. Just like every time you add a new app to your list of INSTALLED_APPS, you always need to run:

$ python migrate

This command will build our database backend with the new models from the OAuth2 package.

Let’s run the application!

$ python runserver

If the application starts correctly, we’ll go to http://localhost:8000/admin/ and login with:

username: adminadmin 
password: adminadmin

When you login successfully, you’ll see a list of different options: Django OAuth Toolkit and Social_Django.

Underneath Django OAuth Toolkit, near Applications, click Add.

Your application should be filled out to be the following:

Client Id: **Do not change**
User: **click the hourglass and select the superuser**
Redirect URIs: **leave blank**
Client Type: “Confidential”
Authorization grant type: “Resource owner password-based”
Client secret: **Do not change**
Name: **Anything you want — maybe “Test Example”**

Next, click save to save that application.

Test the Application

Use either CURL (command line) or use Postman to create a POST request to your web application (http://localhost:8000/auth/token using the following information:


If you are using CURL, you can run the following command:

$ curl -X POST -d "client_id=QKaPafSal2lYYfIYIDSKCC3hoj0TRPLFnZYJNE0h&client_secret=bvQDk9bIwVS28VSNZFP5ehgsrnQroWP5xHccdradOvqxonWSqC1soy7HzaiIiRzCQi73o0pPKyWp7dEoS8DgrZWLoiwJf7iZ8kymv1rb1s3Hx3XSTGQgDmVBqveOQT5H&grant_type=password&username=adminadmin&password=adminadmin" http://localhost:8000/auth/token

If you are using Postman, your interface should look like this:

This will retrieve a secret token for use for authentication by our user.

Now, we need to use the access token that we received and create an Authorization header in the form:

Authorization: Bearer [access_token]

The access token that I received happens to look like this: 71AVaiCidnYcD2ct3Mqgat9j4jo6Xl.

So, if I want to access http://localhost:8000/polls/api/questions/1 I have to create a header using my access token in order to access that question.

In CURL, I would do something like this:

$ curl -H "Authorization: Bearer 71AVaiCidnYcD2ct3Mqgat9j4jo6Xl" -X GET http://localhost:8000/polls/api/questions/1

In Postman I do something like this:

Just to test it out to make sure that I’m doing this right, I will remove the Header from the request and see if Django will let me access the data. Not surprisingly, it doesn’t let me in!

Click here for my Sample Code — remember to install the package using pip

Homework (because this helps you apply what you learned)

  1. Setup a new Django REST Framework web application
  2. Add an endpoint, a serializer and make sure only authenticated users can access the data.
  3. Follow the steps above and try OAuth2 out for yourself. Get it to work.
  4. If you have questions email me

Now, you know how to implement OAuth2 in your own application. You can use the similar steps to get this setup for Facebook, Google, Twitter, Github, etc. so you can allow users to sign in to your application using accounts that they already have and use!

Try this out, see if you can get it work for yourself!

How to Implement Token Authentication with Django REST Framework

Published / by chris / 14 Comments on How to Implement Token Authentication with Django REST Framework

Token Authentication seems to be an Authentication Scheme that gives people the most trouble. The reason appears to be a misunderstanding not of so much how to implement it, but how to actually use it.

For example, the Django REST Framework documentation says that for every request, you have to add an Authorization Header to your requests. But, how do you create that Authorization header?


How do I use Token Authentication to authorize external clients? These are serious questions that I’ve seen from people just like you. But, the difference is that after reading this post, you’ll understand how that works. I’ll show you how to implement Token Authentication using Django REST Framework. Then, I’ll give you a sample application that uses Token Authentication to authenticate users within a Django Application. Best of all, you can take what you learn from my sample code to use in external clients (Javascript clients) to authenticate / authorize users with your RESTful API.

WARNING: NEVER, EVER use Token Authentication without using Secure HTTP (HTTPS). If you want to run my sample code or play around with your own code locally it is OKAY to use Unsecure HTTP (HTTP). However, NEVER do it in production. You’ve been warned.

Introduction to Token Authentication

Token Authentication is a way to authorize users by using an API Key or Auth Token. The way Django REST Framework implements Token Authentication requires you to add a header for each request. This header will be in the following format:

Authorization: Token 93138ba960dfb4ef2eef6b907718ae04400f606a

Authorization is the header key and Token 93138ba960dfb4ef2eef6b907718ae04400f606a is the header value. Note, there is a space between Token and the token itself.

The server where your API lives will read off the user’s token and determine if there is a user assigned to that particular token.

This is Token Authentication in a nutshell. It really doesn’t get anymore complicated than that. The difficulty is implementing it for each of the clients that will use the API (Javascript apps, Desktop apps, Commandline, etc.)

How to Implement Token Authentication

The implementation is a bit more complicated than other Authentication Schemes so take this slow, digest each piece of the puzzle and make sure to download my sample code so you can see what I’m doing each step of the way.

Preliminary Configuration

As with all Django REST Framework Authentication schemes, you must configure the authentication scheme that you will use in your file.



This is where it’s a little different than other Authentication schemes. You will also need to add an app to your INSTALLED_APPS array. The reason for this is because Token Authentication requires a special model called Token which is used to store your user authentication tokens.

In my sample application, my INSTALLED_APPS tuple looks like this:



Now, in order to install the app and update the database with the new Token model, it is imperative that we run python migrate.

Now, you should be ready to create tokens for your users, create a post_save method on your User model so that whenever a new user is added to your database it will automatically create a token for them.

Create Tokens for your Users

Go to your project shell by typing this command at a terminal: python shell. You should be presented with a prompt that looks like this: >>>.

Now, you’re going to type in the following code:

from django.contrib.auth.models import User
from rest_framework.authtoken.models import Token

users = User.objects.all()
for user in users:
    token, created = Token.objects.get_or_create(user=user)
    print user.username, token.key

This code will retrieve all the users that currently exist in your database. It loops through each of them, generates a unique token for each of them and prints our their username and their token. It’s nice to print out their username and the token so you can see that it in fact worked correctly.

Now, you don’t want to manually create tokens for your users whenever a new user registers for your web app so you’ll have to create a special function that will automatically create a token for each new user:


from django.conf import settings
from django.db.models.signals import post_save
from django.dispatch import receiver
from rest_framework.authtoken.models import Token 

@receiver(post_save, sender=settings.AUTH_USER_MODEL)
def create_auth_token(sender, instance=None, created=False, **kwargs):
    if created:

Now, every time a new user is saved in your database, this function will run and a new Token will be created for that user.

Create a Route for Retrieving a Token for Successfully logged in users

Django REST Framework provides a view that simply returns the user’s token when they provide a correct username / password combo.

Let’s add this now:


from django.conf.urls import url
from django.conf import settings
from django.conf.urls.static import static

from . import views as local_view
from rest_framework.authtoken import views as rest_framework_views

urlpatterns = [ 
    # Session Login
    url(r'^login/$', local_views.get_auth_token, name='login'),
    url(r'^logout/$', local_views.logout_user, name='logout'),
    url(r'^auth/$', local_views.login_form, name='login_form'),
    url(r'^get_auth_token/$', rest_framework_views.obtain_auth_token, name='get_auth_token'),
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)

The bottom route is what you should notice:

url(r'^get_auth_token/$', rest_framework_views.obtain_auth_token, name='get_auth_token'),

Now, when POST’ing to http://localhost:8000/accounts/get_auth_token/ with the following data (assuming this username / password exists): { 'username': 'admin', 'password': 'admin' } you’ll receive something that looks like the following: { 'token': '93138ba960dfb4ef2eef6b907718ae04400f606a' }

You’re done implementing Token Authentication. So, what can you do with this Authentication Scheme? Whatever you want. Let’s look at some sample code to see how this works.

I’m launching my e-book very shortly (March 10, 2017). To get additional information, click here.

Click Here to Download the Sample Code

How to use the Sample Code

  1. Unzip the code repository
  2. Change directory to the unzipped code repository
  3. Run the command python runserver
  4. Go to http://localhost:8000/polls/ to run the code.
  5. You’ll be redirected to a very crude login form
  6. Type admin for the username and admin for the password
  7. You’ll be redirected to the polls app and application should work.
  8. Go to http://localhost:8000/accounts/logout to invalidate the cookie that holds the Authentication Token.
  9. Download Postman from
  10. Open Postman. Make sure the dropdown says, “GET”.
  11. Type in: http://localhost:8000/polls/api/questions/1 into the address bar.
  12. Make sure under Authorization “No Auth” is selected.
  13. Under “Headers” add the Header key: Content-Type. Make the Header value: application/json
  14. Click “Send” and you should retrieve "Authentication credentials were not provided."
  15. Now, under “Headers” underneath “Content-Type” add the Header key: Authorization and add the Header value: “Token 93138ba960dfb4ef2eef6b907718ae04400f606a” (without the quotes).
  16. Click “Send” again and you should be getting the correct data.

Homework (If you’d like…)

  1. Look at ALL of my sample code.
    • Underneath the admin form in login.html there is some Javascript that creates a call to http://localhost:8000/accounts/get_auth_token/ with my username and password. When I retrieve the token, I put it into a cookie called “token” and I redirect to the ‘/polls/‘ app.
    • In the app.js file (where my AngularJS code lives), I created an “Interceptor”. The purpose of it is to intercept requests and automatically add a Header with your token so that the Polls Application works correctly. If a request fails, it assumes the user isn’t authorized and redirects to the login form.
  2. Play around with Postman. As long as you keep the Authorization header you can run through the API endpoints and see what you get.
  3. Play with Python Requests. Keep the Django Application running and see if you can write a program using Python Requests that will allow you to login and retrieve some information.

The homework is to help you understand why you would want to use Token Authentication. You can create cool applications external to the Django Application that interface with your API. Give it a go and see what you come up with!

Until next time, Chris

How do I Implement Session Authentication in Django REST Framework?

Published / by chris / 1 Comment on How do I Implement Session Authentication in Django REST Framework?

Introduction to Session Authentication

Session Authentication when used with Django REST Framework allows you to authenticate users very similar to the way Django authenticates users without Django REST Framework.

This will make it extremely easy to introduce a REST API to your web app without having to completely overhaul your authentication system.

The best part of this Authentication Scheme is you literally only have to change ONE line of your Django Application.

Implementation Details (all the little bits…)

In your file, just add 'rest_framework.authentication.SessionAuthentication', to your DEFAULT_AUTHENTICATION_CLASSES setting.



Now, you will be able to login using the normal Django Framework login views / templates, etc or create your own like I did in my sample application below. Also, here is a post about how I like to create authentication in Django.

If you’d like an example of how this is accomplished, I’ve updated the Django Application I used to show you how to implement Basic Authentication using Django REST Framework. Now, it works using Session Authentication.

Click Here to Download the Sample Code

How to use this Sample Code

  1. Unzip the code repository
  2. Change directory to the unzipped code repository
  3. Run the command python runserver
  4. Go to http://localhost:8000/polls/ to run the code.
  5. You’ll be redirected to a very crude login form
  6. Type admin for the username and admin for the password
  7. You’ll be redirected to the polls app and application should work.
  8. Go to http://localhost:8000/accounts/logout to logout of your session.
  9. Go to http://localhost:8000/polls/api/questions/1 to checkout the API (it should tell you that you’re not authenticated to look at the data).
  10. Go to http://localhost:8000/accounts/login and login with admin for the username and admin for the password.
  11. Go back to http://localhost:8000/polls/api/questions/1 and you should be able to see the data now that you are signed in.
  12. My login routes, views and templates are found in my accounts app.

That is the Session Authentication Scheme in a nutshell. I hope you realize how simple it is to implement. Now… for some homework!

Homework (If you’d like…)

  1. Use the sample application and change the static login form into an AJAX style form. (So, when you put in admin for the username and password and click login there should be an AJAX POST request with the username, password and CSRF Token that will attempt to login the user and either send a success message or a failure message. Then, redirect the user back to the /polls/. If you’re unsure how to add a CSRF Token to all AJAX requests, sign up for my FREE Django REST Framework email course below.)

Want to learn how to Implement Token Authentication in Django REST Framework

Example Django App: Social Media NewsFeed

Published / by chris / Leave a Comment

This is a very simple example of a News Feed. You have permission to use this, tinker with it, use it as a template in your own apps.

You can find the source here: News Feed Example

Steps to Run Example:

Step 1: Create a virtual environment

I included a “requirements.txt” file that you can use to install all the dependencies for running the app.

NOTE: if you already have Django 1.9+ installed, you can probably skip this step.

Simply run:

$ virtualenv venv
$ source venv/bin/activate
$ cd news_feed
$ pip install -r requirements.txt

Step 2: Run the Django app

I also included a very light weight Sqlite Database. No need to ‘migrate’ anything.

Go into the Django app and run:

$ python runserver

Step 3: Try out different URLs

There is NO authentication in this system, all you have to do is change the URL to see a different News Feed.

Here are the URLs you can try:




There is also an Admin site that you can use to change the data:


To access the admin site:

Username: admin

Password: adminadmin