DEV Community

JonesOnCorners
JonesOnCorners

Posted on

Series Login-Logout & Authentication in Django --Part I

Django comes with a very comprehensive user authentication module which can be combined with it's fantastic admin module to implement user login and logout modules. In this series my aim is to implement user authentication using various methodologies available to use today. We start of by using the inbuilt Django Authentication.

I strongly suggest everyone starts off by reading the official Django Authentication Docs first which are available at the link Django Authentication.

AUTHENTICATION v/s AUTHORIZATION

It's also almost always good to know what's the difference between authentication and authorization. To explain it in a very simple way, consider you are invited to a party at a colleagues place and are given a invitation card, so you turn up at your friends' place, ring the bell and the friend looks at your invite(yes, he's a very bad friend who doesn't trust you just by looking at you) and lets you in i.e. you are authenticated via the invite he gave you. Once you enter, the friend tells you the party rules and clearly mentions that the party is restricted to the hall and the kitchen, all the rooms upstairs are out of limits, i.e you are authorized to use the hall and the kitchen(and of course the toilets :xD) but not the rooms upstairs. So in technical terms, authentication is allowing entry to a website or an application but authorization is limiting what area of the app you are allowed to access. Authentication and Authorization are implemented by creating users, roles, groups, auth tokens and so on.

As said earlier, Django comes with the auth module pre-installed. Once go through the standard process of creating a django project using the django-adming start project command the settings.py file contains auth module already.
Installed Apps

We also need to add the url to access these login and logout pages the urls.py of our project.

urlpatterns = [
    path('admin/', admin.site.urls),
    path('display/', include('display.urls')),
    path('accounts/', include('django.contrib.auth.urls')), #Add this line to the urls.py of the **PROJECT**

]

Django also provides a very simple but useful login html form which is more than sufficient for getting a hold of the basics. In order to make use of the form we start off by creating the templates folder and within it a registration sub folder. In the registration folder create a login.html file which we will use to render the standard form.as_p login html template.

Directory Structure

Next we move to the settings.py and within that we need to register the templates folder we just created so that all the html files can be clubbed together in this location and are accessible across all applications within our project.Register  templates folder

Now move to the login.html file we just created and add the below lines of code

{% block title %}Login{% endblock %} 
{% block content %}
<h2>Login</h2>
<form method="post">
    {% csrf_token %} {{ form.as_p }}
    <button type="submit">Login</button>
</form>
{% endblock %}

This code will render
1) A page titled Login
2) A form with two text fields Username and Password and a login button.
3) The button on click makes a HTTP POST request.

Alt Text

Now, you can use this screen to login via a user which can be easily created using the django admin console. The database table which the user is authenticated once we login is the auth_user, which Django implicitly generates when we do our first migration when we create a django project. I will probably do a Django project starter tutorial later to cover this part. Once you enter the credential and hit enter you'll notice that you get a HTTP 404, the reason is your Django application doesn't really have a redirect function as of now, as in it doesn't know what to do on successful login. In order to handle that let's create a default landing page called home.html where we can redirect upon login.

In the templates base folder(not the registration sub folder) we'll create a file home.html* which will display a simple welcome message and also allow the user to logout so that we can complete the whole login-logout toggle. We will also modify the project urls.py to add the home page view and also modify the settings.py to add two more parameters at the end LOGIN_REDIRECT_URL and LOGOUT_REDIRECT_URL essentially telling Django what to do when the user chooses to logout.

The code of the home.html is designed to handle both login and logout, i.e. if the user is logged in it displays a simple 'Welcome !!!' user message and provides a logout link which uses the Django logout template. If the user logs out we simply display a message and provide a link back to the login page.

{% extends 'base.html' %} {% block title %} HOME {% endblock %} 
{% block content%} 
    {%if user.is_authenticated %} 
        Welcome {{ 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 %} {% endblock %}

Final urls.py

from django.contrib import admin
from django.urls import path, include
from django.views.generic.base import TemplateView

urlpatterns = [
    path('admin/', admin.site.urls),
    path('display/', include('display.urls')),
    path('accounts/', include('django.contrib.auth.urls')),
    path('', TemplateView.as_view(template_name ='home.html'), name = 'home'),

]

Add below parameters to the settings.py

LOGIN_REDIRECT_URL ='home'
LOGOUT_REDIRECT_URL = 'home'

Alt Text
Alt Text
Alt Text

So this is the most basic authentication functionality provided by Django which is powerful enough to implement for a beginner level project or even at a small college level.

Top comments (0)