Author Archives: chris

How to Override TokenAuthentication Backend to detect an expiring token

Published / by chris / Leave a Comment

Why would you want to keep your tokens around forever?

You don’t want to give away tokens that last forever when you’re authenticating because what that means for your users is that, if a token is stolen, an attacker will be able to login as long as your user’s token exists in the database. This is why JWT might seem to be “BETTER” than Token Authentication.

Token Auth with expiring tokens is a breeze

You definitely don’t know need to implement JWT in order to get the security of JWT. Token Authentication expiring tokens are a breeze and you’ll see the simplest way to implement them.

Determine how long you want your users to stay authenticated

This ends up being a question between usability, or how often would a user want to login and security. Obviously, you don’t want to keep a user logged in forever otherwise, an attacker could steal a user’s token and stay logged in on your user’s account forever.

On the other hand, it’s nice when you don’t have to continue to log in every time you want to to connect. When was the last time your had to log into Facebook?

A good rule of thumb is 2 weeks to 30 days.

Create a new Setting with that specific length of time

This is an arbitrary naming scheme that you can remember like, TOKEN_EXPIRE_TIME (or similar).

You always want to keep these constants in the setting.py file because you can update functionality in one place and it will automatically update how sections of your code works.

Here’s an example of setting expiring time:

settings.py

import datetime
TOKEN_EXPIRE_TIME=datetime.timedelta(days=30)

Override the TokenAuthentication Class to check validation

Now, you need to override the Token Authentication class so that every time Django REST Framework trying to authenticate you, our TokenAuthentication backend will check to see if your token is valid based on our TOKEN_EXPIRE_TIME setting.

So, here is our new backend. Remember to update your DEFAULT_AUTHENTICATION_CLASSES.

authentication.py

from rest_framework.authentication import TokenAuthentication, get_authorization_header
from rest_framework.exceptions import AuthenticationFailed
from django.conf import settings
import pytz

class ExpiringTokenAuthentication(TokenAuthentication):
    def authenticate_credentials(self, key):
        try:
            token = self.model.objects.get(key=key)
        except self.model.DoesNotExist:
            raise exceptions.AuthenticationFailed('Invalid token')

        if not token.user.is_active:
            raise exceptions.AuthenticationFailed('User inactive or deleted')

        utc_now = datetime.utcnow()
        utc_now = utc_now.replace(tzinfo=pytz.utc)

        if token.created < utc_now - settings.TOKEN_EXPIRE_TIME:
            raise exceptions.AuthenticationFailed('Token has expired')

        return token.user, token

Conclusion

This is an example of how you could override TokenAuthentication backend so that you can detect if your token is expired. The next thing you would need to do is create a new token for your users the next time they login.

Token Authentication can be a very robust authentication method. It’s up to you to figure out the best way to override Token Authentication to suit your needs because Token Authentication doesn’t do everything it should out of the box.

If you want to learn more about how to override Token Authentication so that it’s more robust, more secure and works better, you don’t have to guess any longer. I’m writing an ebook that will teach you these techniques in Token Authentication.

Want to learn more? Click here to learn about my book I’m writing. I’m launching soon! So, get it while it’s hot!

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.

settings.py

INSTALLED_APPS = (
    #...
    'oauth2_provider',
    'social_django',
    'rest_framework_social_oauth2,
)

Next, let’s include the URLs to our urls.py.

urls.py

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.

settings.py

TEMPLATES = [
    {
        # ...
        'OPTIONS': {
            'context_processors': [
                # ...
                'social_django.context_processors.backends',
                'social_django.context_processors.login_redirect',
            ],
        },
    }
]

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

settings.py

TEMPLATE_CONTEXT_PROCESSORS = (
    # ...
    'social_django.context_processors.backends',
    'social_django.context_processors.login_redirect',
)

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.

settings.py

# DJANGO REST FRAMEWORK SETTINGS
REST_FRAMEWORK = {
    # ...
    'DEFAULT_AUTHENTICATION_CLASSES': (
        # ...
        'oauth2_provider.ext.rest_framework.OAuth2Authentication',
        'rest_framework_social_oauth2.authentication.SocialAuthentication',
    ),
}

# DJANGO SETTINGS 
AUTHENTICATION_BACKENDS = (
    # ...
    'rest_framework_social_oauth2.backends.DjangoOAuth2',
    'django.contrib.auth.backends.ModelBackend',
)

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 manage.py migrate

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

Let’s run the application!

$ python manage.py 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:

username=adminadmin
password=adminadmin
client_id=QKaPafSal2lYYfIYIDSKCC3hoj0TRPLFnZYJNE0h
client_secret=bvQDk9bIwVS28VSNZFP5ehgsrnQroWP5xHccdradOvqxonWSqC1soy7HzaiIiRzCQi73o0pPKyWp7dEoS8DgrZWLoiwJf7iZ8kymv1rb1s3Hx3XSTGQgDmVBqveOQT5H
grant_type=password

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 Custom Authentication with Django REST Framework

Published / by chris / Leave a Comment

Introduction to Custom Authentication

Custom Authentication in Django REST Framework is the way you would create any time of authentication you would want. In fact, inside of the internals of DRF, you will find every other authentication scheme that I’ve talked about using CustomAuthentication. So, let’s look at an example of how you would implement something like this.

How to Implement Custom Authentication

WARNING: The example I’m about to show you is VERY VERY bad for security so DON’T use it in production. 🙂

First, you will need to override the BaseAuthentication class. It looks like this:

my_proj/accounts/auth.py from django.contrib.auth.models import User from rest_framework.authentication import BaseAuthentication from rest_framework import exceptions

class MyCustomAuthentication(BaseAuthentication):
    def authenticate(self, request):
        username = request.GET.get("username")

        if not username: # no username passed in request headers
            return None # authentication did not succeed

        try:
            user = User.objects.get(username=username) # get the user
        except User.DoesNotExist:
            raise exceptions.AuthenticationFailed('No such user') # raise exception if user does not exist

        return (user, None) # authentication successful

I called the new class MyCustomAuthentication. If you look at what this does, it retrieves a username as a GET request and will try to find a user with that username. (You should now understand why this is a stupid example).

Next, in settings.py you’ll want to update the DEFAULT_AUTHENICATION setting.

settings.py REST_FRAMEWORK = { ‘DEFAULT_AUTHENTICATION_CLASSES’: ( ‘accounts.auth.MyCustomAuthentication’, ), ‘DEFAULT_PERMISSION_CLASSES’: ( ‘rest_framework.permissions.IsAuthenticated’, ) }

And that is LITERALLY all you need to do to create a new authentication scheme. Download the custom code below and try going to the following URL:

http://localhost:8000/polls/api/questions/1/?username=chris

You should be able to see the data. Also, if you go to:

http://localhost:8000/polls/api/questions/1/

The authentication scheme should deny you from getting any data at all.

Click Here to Download the Sample Code

Homework

  1. Run the sample code and go to the two URLs above.
  2. Try to implement your own Session Authentication scheme WITHOUT enforcing CSRF tokens using Custom Authentication. You can see how Session Authentication is implemented here

How to Implement Token Authentication with Django REST Framework

Published / by chris / Leave a Comment

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?

Also…

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 settings.py file.

myproject/settings.py

REST_FRAMEWORK = { 
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework.authentication.TokenAuthentication',
    ),
    'DEFAULT_PERMISSION_CLASSES': (
        'rest_framework.permissions.IsAuthenticated',
    )
}

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:

myproject/settings.py

INSTALLED_APPS = ( 
    'django.contrib.admin', 
    'django.contrib.auth', 
    'django.contrib.contenttypes', 
    'django.contrib.sessions', 
    'django.contrib.messages', 
    'django.contrib.staticfiles',
    'polls',
    'accounts',
    'rest_framework',
    'rest_framework.authtoken',
)

Now, in order to install the app and update the database with the new Token model, it is imperative that we run python manage.py 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 manage.py 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:

myproject/accounts/models.py

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:
        Token.objects.create(user=instance)

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:

myproject/accounts/urls.py

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.

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 manage.py 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 https://www.getpostman.com/
  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

3 Things You Need to Authenticate Users in Django

Published / by chris / Leave a Comment

You want to authenticate users but you’re unsure how. The documentation isn’t the most helpful thing in the world. You think, “wow… this documentation assumes I know all this other stuff…”

What are the things you need to authenticate users? There are 3 things you need and I’m going to show you what each looks like.

First: You need some routes

You need authentication routes. I think it makes the most sense to create a separate app for this purpose. (Separate all your login logic from all your other logic)

Let’s look at some login routes:

_loginapp/urls.py

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

from . import views

urlpatterns = [
    # Session Login
    url(r'^login/$', views.login_user, name='login'),
    url(r'^logout/$', views.logout_user, name='logout'),
    url(r'^auth/$',  views.login_form, name='login_form'),
]

Second: You’ll need some templates

Templates are important. Templates are the HTML representation of your application. For example, at the bare minimum, you’ll need a way to let your users login. How do you do it? It doesn’t have to be pretty because this is JUST HTML.

loginapp/templates/loginapp/login.html

<form method='post' action="{%  url 'loginapp:login' %}">
    <label for="username">Username:</label>
    <input type="text" name="username" />
    <br>
    <label for="password">Password:</label>
    <input type="password" name="password" />
    <br>
    <input type="submit" value="Login" />
</form>

Third: You’ll need some views

The views you’ll need for login will be:
1. The login form view (shows the login form)
2. The POST view that will authenticate a user that is active / exists
3. A view that will log the user out

Let’s start with the login form view (loginapp/auth):

def login_form(request):
    return render(request, 'accounts/login.html', {})

This view simply renders our login.html template that we created above. It’s also possible to make only 2 routes (1 that will detect a POST request and 1 that will detect a GET request) however, I (personally) really like have separate views for each request method.

Here is an example of a view that will detect a username and password and use those credentials to authenticate a user and login the user thus creating a session specifically for that user.

def login_user(request):
    username = request.POST.get('username')
    password = request.POST.get('password')
    user = authenticate(username=username, password=password)
    if user is not None:
        # the password verified for the user
        if user.is_active:
            login(request, user)
            return redirect('/polls/')
    return redirect(settings.LOGIN_URL, request)

This method will get the username and password from the POST request data. Then, we will use the username and password to try to authenticate a user that exists in our database.

If a user exists, we will try to login our user and redirect to our polls application. If the user does not exist we will redirect back to the login form.

How do you logout an authenticated user?

def logout_user(request):
    logout(request)
    return redirect('/polls/')

This method will take the request object and user it to logout the logged in user. Once the user logs out, the application will redirect the user to our polls application.

This is the 3 things that you need to authenticate users in your Django application. (If you want to use Session Authentication with Django REST Framework) this is how you would accomplish this.

I hope that helps you when need to authenticate users in your future web application.

How do I Implement Session Authentication in Django REST Framework?

Published / by chris / Leave a Comment

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 settings.py file, just add 'rest_framework.authentication.SessionAuthentication', to your DEFAULT_AUTHENTICATION_CLASSES setting.

myproject/settings.py

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework.authentication.SessionAuthentication',
    ),
    'DEFAULT_PERMISSION_CLASSES': (
        'rest_framework.permissions.IsAuthenticated',
    )
}

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 manage.py 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

List of Authentication Schemes available for Django REST Framework

Published / by chris / Leave a Comment

Do you know what your options are?

You learned a little bit of how authentication works with Django REST Framework from my short, FREE mini email course. What you might NOT know is that Basic Authentication isn’t the only type of authentication available do you.

You can use the following authentication schemes in Django REST framework and keep checking your inbox for implementation details for each of these authentication schemes.

The list of Authentication types in Django REST Framework

  1. Basic Authentication — you learned how to implement this while following my free email course. If you haven’t signed up for the email course yet, put your email address in the form at the end of this post.
  2. Session Authentication — this is similar to the authentication that Django uses to authenticate users.
  3. Token Authentication — Token Auth is how most APIs authenticate users. You might have played around some APIs that require an “API Key”. This is how you would implement that for your users.
  4. Custom Authentication — If for some reason, the other authentication schemes don’t do what you want, you can override the BaseAuthentication class and create your own authentication scheme in Django REST Framework.
  5. OAuth2 Authentication — OAuth authentication is a way to allow your users to authenticate using things like Social Media. I’m sure you’ve logged into certain web apps that allowed you to authenticate using Google or Facebook. This allows you to do that!

Which Authentication scheme is best for me?

That will depend on your specific use case. If you know how to implement each of them, you’ll be better off in the long run. Come back to this post periodically. Each of the authentication schemes above will eventually link to a post that will show you EXACTLY how to implement each one.

If you’d rather not come back for each post, simply put your email in the box below and you’ll get every new post sent directly to your inbox!

SQLite Doesn’t Care About Your max_length

Published / by chris / Leave a Comment

SQLite databases don’t care about your using of max_length on your models. Let’s look at an example.

models.py

class Book(models.Model):
    title = models.CharField(max_length=30)

Now, we’ll run some queries.

$ ./manage.py makemigrations
$ ./manage.py migrate
$ ./manage.py shell
>>> from book.models import Book
>>> title = 'A' * 31
>>> print len(title)
31
>>> book = Book.objects.create(title=title)
>>> book.save()
>>> len(book.title)
31

When running SQL queries using SQLite, you find that you can create records and the database will save a CharField with attributes with bigger strings than what the max_length describes.

Is there any way we can fix this? Sure there is!

One way that we can validate if our model instance is correct is to run a method called full_clean().

So, what we can do is override our save() method so that we can validate our SQLite model before we save our model. Let’s take a look.

class Book(models.Model):
    title = models.CharField(max_length=10)

    def save(self, *args, **kwargs):
        try:
            self.full_clean()
            super(Book, self).save(*args, **kwargs)
        except:
            print "Error saving model"

As you can see, if self.full_clean() throws an error, our instance will print out ‘Error saving model’ and our save method will not save our record to the database.

Try this out next time you use SQLite for your database.

I hope that works for you!

Chris

Why Tutorials Suck

Published / by chris / Leave a Comment

When was the last tutorial you’ve taken? It could have been my Free Email Course about Django REST Framework, or it could have been the “Official Django Tutorial” that will have you go through a simple Django Application.

What did you think about these tutorials? Which one helped you to learn the best? Why did it help you learn?

I’m not saying my course is the best, ever. Far from it. However, it was an experiment to see if tutorials can be better, or not.

This is an opinion piece about my feelings about tutorials and how it might be possible to make them better.

Tutorials Don’t Help you Learn

Tutorials don’t really help you learn how to use the technology that you want to learn. Every tutorials is an overview to show how the technology works, how easy it is to get up to speed, and gets you excited to read the documentation so you can learn more.

You will get a broad overview of the technology in question, and after you’re finished with the tutorial, you might try to create an app of your own. But, how well do you do? Does it work out? After creating the Polls App, how confident were you to create your own app?

“Type This Here then run it and see what happens”

Look at the Official Django Tutorial. Here is a small snippet of it:


Let’s write the first view. Open the file polls/views.py and put the following Python code in it:

polls/views.py

from django.http import HttpResponse


def index(request):
    return HttpResponse("Hello, world. You're at the polls index.")

This is a typical example of, “Hey! Go to this page and type this here.”

Afterwards, it doesn’t tell you to run the application. The tutorial makes sure the application will run correctly before it tells you to run it. This is completely backwards.

There is A LOT you can learn by running the application at this point. You will get an error!! But, later, you’ll understand why you’re getting that error.

As an example, my email course had a few errors in it that you won’t know or understand until later in the course. I did this very blatantly. For the reader, it would be really hard to put 2 and 2 together and your understanding wouldn’t be as strong if you didn’t see the outcome of the errors. Then, also, you learned how to fix the issue!

It that makes sense, read on. I’ll show you how to make your tutorials better.

Fix your Tutorials, Here’s how

If you want to create a tutorial, here’s some things you can do to make it better for people to learn from.

Introduce them to common errors

While you are doing the, “Write this code here…” lessons, have your readers run the code so that they can see common issues. If the Official Django Tutorial told you to try to run the code after your created your first view, you would learn that in order for your app to work, you need a URL pattern to access it.

Imagine if the tutorial forgot to tell you to import a builtin Django function. Then, you ran the app. You’d learn exactly what error you get and you’ll be able to learn how to fix it.

Learning what common errors look like, you’d learn exactly what needs to be fixed in your app to fix the error.


FIX: Force your readers to see common errors. Over the course of the material, your readers will understand exactly how to fix them.


Let them figure some things out on their own

Don’t tell your readers everything. Let them do some work to figure things out on their own. That way, they will learn how to search for information and how to use the information to modify an existing application. That skill is indispensible.

One great way to do this, is to by creating Homework. Homework is a great way to have your readers learn the material better by getting out of their comfort zone and learn new material on their own.

This brings me to the third lesson.


FIX: Give your reader some homework to do. The ability to find information and know how to use that information to modify an existing app does wonders for teaching somebody how to use the technology you are teaching


Be available for feedback

If you give your reader homework, you HAVE to be there for questions and answers. Email works really well.

If you’re not there for feedback, you are leaving your readers behind. I tell everybody who takes my email course that they can email me their questions and I read and answer every email I receive.


FIX: Be available for feedback. If your readers have questions they deserve to ask you to clear up anything you are teaching them.


Give the application away so they can compare their code

It’s very possible that your reader is going to make some errors in their code and it’s going to be really annoying not knowing what happened that caused these errors.

Most of the time it’s a simple typo that can break the entire application. Try finding that typo in thousands of lines of code! In a simple tutorial with less than a few hundred lines of code, a typo is unacceptable.


FIX: Send your readers the exact code that you used for that lesson. This will allow them to check their code with yours. A simple diff my_app your_app will show you where your typos are.


Make bad tutorials better

So, if you’re going through a tutorial how can you use the above fixes to make it better while you’re going through it?

  1. Find groups of readers who took the tutorial so you can ask them for help and, if they are willing, their working examples of the project.
  2. Come up with some cool ideas that you want to implement and search the Googles for information about how to implement these ideas. Don’t wait for someone else to tell you what you should be implementing.
  3. Don’t be afraid to run the application midway through the tutorial. You can learn a lot by just reading error messages and attempt to fix them before you move on with the rest of the tutorial. Doing things by yourself is more important for your learning than simply copying code.

Excited to take your next tutorial? Sign up below for a free Django REST Framework tutorial!

Why Do You Want to Learn Django REST Framework?

Published / by chris / Leave a Comment

If you do a tiny bit of lurking on Django forums, it seems like EVERYBODY is going nuts over learning how to create a RESTful API in Django using Django REST Framework. I’m fastinated by this craze. So, I wanted to start a conversation about why YOU might want to learn how to create a RESTful API.

You might want to pay attention, I have a fun surprise at the end of this post.

So, you crazy people and your new fangled RESTful API technologies, need to understand what you need to know about REST and why it might make sense to use it.

Reasons for creating an API

You have probably heard about REST and APIs while reading about how that cool new tech startup created that amazing website. It seems like everything COOL online is written in pure Javascript.

That awesome Single Page Application looks so cool how it feels like a desktop application. It’s seamless, it’s fast and I want to do that SAME THING!!

Besides creating cool apps, here is why you might want to learn REST and Django REST Framework for that matter.

1. Domain Independence

If you only had a REST API, what would you be able to do with it?

Maybe you want to integrate your web presence into a mobile app. You can use your API to make your app do all the cool things your web app can do, but now you have piece of software people can install into their phones and get all your snazzy widgets quicker and easier than ever!

What if you wanted to create a desktop application (Not sure why you would…) but, you’d be able to send data back to your server directly from your amazing software.

Some people and companies even sell usage for their API. You could potentially charge people to use your API so they can create their own awesome apps.

Literally, the sky is the limit.

2. Programming Language Independence

This falls in line with the above. Think you need to follow the same programming language to get your REST API working in other domains? For example, if you’re using Django to create your REST API, do you need to use Django to work with it? Absolutely not!

You could use any programming language and integrate your API with it.

  • Create an Android App using Java
  • Create an iOS App using Objective-C or Swift
  • Create a Desktop application using Python or C++
  • Create a Single Page Application with your API using Javascript
  • The choice is yours!

3. It scales great!

You can layer as much as you need between client and server. Want a load balancer? Caching Mechanism? Special routing needs?

It’s not difficult to get things working with a REST API.

Just a reminder, don’t forget that if you’re using the REST API for too many things, you’ll definitely have problems with bandwidth and latency issues.

Doesn’t REST Sound Fun?

I hope the above helps you decide if you should be learning Django REST Framework. It’s a lot of fun and you can do SO MUCH with it!

If for nothing else but to put on your resume that you understand how to create RESTful APIs and some experience with Django REST Framework, I’ve created an email course that will walk you through creating an API with Django REST Framework.

You’ll learn how to take that “Polls App” that you created with the Official Django Tutorial and we are going to extend it with a RESTful API.

Then, as a special BONUS lesson, you will learn how to USE the API using AngularJS because, why LEARN to create a RESTful API if you don’t know how to use it? Am I right?!

Sign up below! The first lesson will reach your inbox shortly!!