Brainstorm's snippets (1/226)

  How to Use Django's Built-in Login System

Adapted to Django 2.1 from:

https://simpleisbetterthancomplex.com/tutorial/2016/06/27/how-to-use-djangos-built-in-login-system.html

Pre-requisites

INSTALLED_APPS = [
    ...
    'django.contrib.auth',
    ...
]

MIDDLEWARE = [
    ...
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    ...
]

Login

Configure the urls used by Django for login and redirection after successfull login:

file "settings.py":

LOGIN_URL = '/login/'
LOGIN_REDIRECT_URL = '/'
LOGOUT_URL = '/logout/'

Configure the URL routes

file "urls.py":

from django.urls import path
from django.conf import settings
from django.urls import include, path, re_path
from django.contrib.auth import views as auth_views


urlpatterns = [
    ...
    path('login/', auth_views.LoginView.as_view(template_name="accounts/login.html"), name="login"),
    ...
]

Create a login template

file "accounts/login.html":

{% extends 'base.html' %}

{% block title %}Login{% endblock %}
{% block body-class %}login{% endblock %}

{% block content %}

    <form method="post">
        <h2>Please sign in</h2>
        {% csrf_token %}
        {{ form.as_p }}
        <div class="submit-row">
            <button class="btn btn-lg btn-primary" type="submit">Login</button>
        </div>
    </form>

{% endblock %}

where (Bootstrap):

/*
 * Login form
 */

body.login form {
    width: 100%;
    max-width: 330px;
    padding: 15px;
    margin: 80px auto;
}

body.login form p {
    padding: 0;
    margin: 0;
}

body.login form input {
    height: auto;
    padding: 10px;
    font-size: 16px;
}

body.login form label {
    padding: 10px;
    width: 30%;
}

body.login h2,
body.login .submit-row {
    margin: 0 auto;
    text-align: center;
    margin: 30px 0;
}

Logout

In the URL routes, you can either have the logout view render a specific template:

urlpatterns = [
    ...
    path('logout/', auth_views.LogoutView.as_view(template_name="accounts/logged_out.html"), name='logout'),
    ...
]

or use the next_page parameter to redirect either to a specific target:

urlpatterns = [
    ...
    path('logout/', auth_views.LogoutView.as_view(next_page=settings.LOGIN_REDIRECT_URL), name='logout'),
    ...
]