DEV Community

Shakhzhakhan Maxudbek
Shakhzhakhan Maxudbek

Posted on • Originally published at args.tech

Implementing user authentication in Django

For protecting data in views from anonymous users you need to use authenticating system. Django provides built-in functions for auth implementation (documentation).

What is authentication? Authentication - process of user identification data comparison. Authentication passes in two steps:

  • User identification - searching in database entered username.
  • Authentication. If username from first step exists, system comparing value from "password" field in HTML page with password, saved in database. Before comparison password must be hashed, because database not storing raw password.

Open your Django project and follow this steps:

Create "sign_in" function in views.py:

from django.contrib.auth import authenticate, login
from django.shortcuts import redirect


def sign_in(request):
    username = request.POST['username']
    password = request.POST['password']
    user = authenticate(request, username=username, password=password)
    if user is not None:
        login(request, user)
        return redirect('core:profile')
    else:
        return redirect('core:sign-in')
Enter fullscreen mode Exit fullscreen mode

Create login.html file in "templates" directory:

<form method="post" action="{% url 'login' %}">
    {% csrf_token %}
    <table>
        <tr>
            <td>{{ form.username.label_tag }}</td>
            <td>{{ form.username }}</td>
        </tr>
        <tr>
            <td>{{ form.password.label_tag }}</td>
            <td>{{ form.password }}</td>
        </tr>
    </table>

    <input type="submit" value="login">
</form>
Enter fullscreen mode Exit fullscreen mode

Now you need to create url for authentication in urls.py:

from django.urls import path
from .views import sign_in


app_name = 'core'

urlpatterns = [
    path('sign-in/', sign_in, name='sign-in'),
]
Enter fullscreen mode Exit fullscreen mode

Configuring URL patterns in settings.py:

LOGIN_REDIRECT_URL = '/accounts/profile/'
LOGIN_URL = '/accounts/login/'
LOGOUT_REDIRECT_URL = '/'
Enter fullscreen mode Exit fullscreen mode

When you need restrict some data, not entire view, use is_authenticated method. Programmatically checking in view, is user authenticated:

if request.user.is_authenticated:
    # Do something for authenticated users.
    ...
else:
    # Do something for anonymous users.
    ...
Enter fullscreen mode Exit fullscreen mode

Checking if user is authenticated in templates:

{% if user.is_authenticated %}
    <p>Your account doesn't have access to this page. To proceed, please login with an account that has access.</p>
{% else %}
    <p>Please login to see this page.</p>
{% endif %}
Enter fullscreen mode Exit fullscreen mode

Additionally you may decorate view with login_required:

from django.contrib.auth.decorators import login_required


@login_required(redirect_field_name='login_page')
def my_protected_view(request):
    ...
Enter fullscreen mode Exit fullscreen mode

Top comments (0)