Django comes out-of-the-box with a powerful user authentication system. This tutorial covers its basic usage for creating a login and logout page. Subsequent tutorials cover how to register a new user) and reset passwords.

Start a new Django project

Let’s create a simple Django project to demonstrate how little code it takes to implement a login form with Django’s built-in user authentication app.

On the command line enter the following code to create a new directory for our code (Desktop/users_tutorial), enter a new virtual environment called users, install Django, and start a new project called my_project.

$ mkdir ~/Desktop/users_tutorial
$ cd ~/Desktop/users_tutorial
$ python3 -m venv ~/.virtualenvs/users
$ source ~/.virtualenvs/users/bin/activate
(users) $ pip install django
(users) $ django-admin.py startproject my_project .
(users) $ ./manage.py migrate
(users) $ ./manage.py runserver

If you navigate to http://127.0.0.1:8000 you’ll see the friendly Django welcome screen.

Django welcome page

Basic Login

Django provides us with a default view for a login page via LoginView. All we need to add are a urls.py file for the auth system, a login template, and a small update to our settings.py file.

First update the urls.py file to add the Django auth app:

# my_project/urls.py
from django.conf.urls import include, url
from django.contrib import admin

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^users/', include('django.contrib.auth.urls')),
]

As the LoginView documentation notes, by default Django will look within a templates folder called registration for a file called login.html for a login form. So we need to create a new directory called registration and the requisite file within it. From the command line type Control-C to quit our local server. Then enter the following:

(users) $ mkdir templates
(users) $ mkdir templates/registration
(users) $ touch templates/registration/login.html

Use the following template code:

<!-- templates/registration/login.html -->
<h2>Login</h2>
<form method="post">
  {% csrf_token %}
  {{ form.as_p }}
  <button type="submit">Login</button>
</form>

We’re using HTML <form></form> tags, specifying the POST method since we’re sending data to the server (we’d use GET if we were requesting data, such as in a search engine form). We add {% csrf_token %} for security concerns, namely to prevent a XSS Attack. The form’s contents are outputted between paragraph tags thanks to {{ form.as_p }} and then we add a “submit” button.

The final step is to update our settings.py file. We need to tell Django where to find our newly created templates folder. Update the DIRS setting within TEMPLATES as follows. This is a one-line change.

# settings.py
TEMPLATES = [
    {
        ...
        'DIRS': ['templates',],
        ...

    },
]

And we need to specify where to redirect the user upon a successful login. We can set this with the LOGIN_REDIRECT_URL settings. At the bottom of the settings.py file add the following:

# settings.py
LOGIN_REDIRECT_URL = '/'

We’re actually done at this point! But there’s one missing piece: we haven’t created any users yet. Let’s quickly do that by creating a superuser from the command line by running the command ./manage.py createsuperuser and answering the prompts. Note that your password will not appear on the screen when typing for security reasons.

(users) $ ./manage.py createsuperuser
Username (leave blank to use 'wsv'):
Email address: [email protected]
Password:
Password (again):
Superuser created successfully.

If you now start up the Django server again with ./manage.py runserver and navigate to our login page at http://127.0.0.1:8000/users/login/ you’ll see the following.

Login page

Upon entering the login info for our just-created user, we are redirected to the homepage.

Homepage error

We know that our login worked because we were redirected to the homepage, but we haven’t created it yet so we see the error Page not found.

Create a homepage

Let’s add a simple homepage that will display one message to logged out users and another to logged in users.

First quit the local server with Control-c and then create new base.html and index.html files.

(users) $ touch templates/base.html
(users) $ touch templates/index.html

Add the following code to each:

<!-- templates/base.html -->
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>{% block title %}Django Login{% endblock %}</title>
</head>
<body>
  <header>
    <h1>Django Login</h1>
    {% if user.is_authenticated %}
      Hi {{ user.username }}!
    {% else %}
      <p>You are not logged in</p>
      <a href="{% url 'login' %}">login</a>
    {% endif %}
  </header>
  <main>
    {% block content %}
    {% endblock %}
  </main>
</body>
</html>
<!-- templates/index.html -->
{% extends 'base.html' %}

{% block title %}Login{% endblock %}

{% block content %}
  <p>Logged-in screen</p>
{% endblock %}

Update our urls.py file so we display the homepage:

# my_project/urls.py
from django.conf.urls import include, url
from django.contrib import admin
from django.views.generic.base import TemplateView

urlpatterns = [
    url(r'^$', TemplateView.as_view(template_name='index.html'), name='index'),
    url(r'^admin/', admin.site.urls),
    url(r'^accounts/', include('django.contrib.auth.urls')),
]

And we’re done. If you start the Django server again with ./manage.py runserver and navigate to the homepage you’ll see the following:

Homepage logged in

It worked!

Let’s add a logout link to our page so users can easily toggle back and forth between the two states.

In our base.html file add a one-line link for logging out.

<!-- templates/base.html-->
...
  <header>
    <h1>Django Login</h1>
    
      Hi {{ user.username }}!
      <p><a href="{% url 'logout' %}">logout</a></p>
    {% else %}
      <p>You are not logged in.</p>
      <p><a href="{% url 'login' %}">login</a></p>
    {% endif %}
  </header>
...

And update settings.py to provide a redirect link for logging out which is called, appropriately, LOGOUT_REDIRECT_URL. We can add it right next to our login redirect so the bottom of the file should look as follows:

# my_project/settings.py
LOGIN_REDIRECT_URL = '/'
LOGOUT_REDIRECT_URL = '/'

If you refresh the homepage you’ll see it now has a “logout” link for logged in users.

Homepage logout link

And clicking it takes you back to the homepage with a “login” link.

Homepage logged out

Conclusion

With very little code Django allowed us to setup a login and logout system. In the next post, Django User Authentication Tutorial Part 2: Signup) we’ll learn how to add a signup page to register new users.




If you’d like to learn more about Django and build step-by-step multiple web applications, check out the free online book I wrote Django For Beginners.