Creating login and logout system in Django



We will start this tutorial by creating Login template, then we will create a url path for login pointing to login view which will direct user to login template. After finishing this we will create a logout system using which logged in user can log out.

First, we will create a login page template in the same template folder where we created home.html and signup.html.

<!DOCTYPE html>

<html lang="en" dir="ltr">

  <head>

    <meta charset="utf-8">

    <title>Login</title>

  </head>

  <body align="center">

    <br/>

    {% if msg %}

    {{msg}}

    {% endif %}

    <br/>

    <h2> Login page!</h2>

    <form action="" method="post">

      {% csrf_token %}

      <label>Username</label><br/>

      <input type="text" name="username" required><br/><br/>

      <label>Password</label><br/>

      <input type="password" name="password" required><br/><br/>

      <input type="submit" value="Login">

    </form>

  </body>

</html>

In accounts/urls.py add path for login views

path('login/',views.login_page,name='login'),

In accounts/views.py define a view for login request.

def login_page(request):

    if request.method=="POST":

        username=request.POST['username']

        password=request.POST['password']

        user=authenticate(request,username=username,password=password)

        if user is None:

            msg="Invalid Username or Password"

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

        else:

            login(request,user)

            return redirect('home')

    else:

        return render(request,'accounts/login.html')

Now visit http://127.0.0.1:8000/login/

Enter the credentials and you will land up in Home Page

Now we will create a logout system

Add logout url path in accounts/urls.py.

from django.urls import path

from . import views

urlpatterns = [

    path('',views.home,name='home'),

    path('signup/',views.signup,name='signup'),

    path('login/',views.login_page,name='login'),

    path('logout/',views.logout_page,name='logout'),

 ]

 

Add logout view to accept the logout request in accounts/views.py.

from django.shortcuts import render,redirect

from django.contrib.auth import authenticate,login,logout

from django.contrib.auth.models import User

 

def home(request):

    return render(request,'accounts/home.html')

 

def signup(request):

    if request.method=="POST":

        username=request.POST['username']

        fname=request.POST['fname']

        lname=request.POST['lname']

        password1=request.POST['password1']

        password2=request.POST['password2']

        if password1 != password2:

            msg="password did not match"

            return render(request,'accounts/signup.html',{'msg':msg})

        else:

            try:

                user=User.objects.get(username=username)

                msg="username already exists"

                return render(request,'accounts/signup.html',{'msg':msg})

            except User.DoesNotExist:

                user=User(username=username,password=password1,first_name=fname,last_name=lname)

                user.save()

                login(request,user)

                return redirect('home')

    else:

        return render(request,'accounts/signup.html')

 

def login_page(request):

    if request.method=="POST":

        username=request.POST['username']

        password=request.POST['password']

        user=authenticate(request,username=username,password=password)

        if user is None:

            msg="Invalid Username or Password"

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

        else:

            login(request,user)

            return redirect('home')

    else:

        return render(request,'accounts/login.html')

 

def logout_page(request):

    logout(request)

    return redirect('home')

 

Now add this logout url in home page(home.html)

<html>

<head>

  <title>Home</title>

</head>

<body align="center">

  <br/>

  <h2>This is our home page</h2><br/><br/><br/>

  {% if user.is_authenticated %}

  <h3> Hello {{user.first_name}}</h3>

  <a href="{% url "logout" %}">Logout</a><br/><br/>

  {% else %}

  <a href="{% url "signup" %}">Register</a><br/><br/>

  <a href="{% url "login" %}">Login</a>

  {% endif %}

</body>

</html>

Logout link will only appear when user is already logged in similarly login and Register link will appear when the user is not already logged in.

With this we have successfully completed our series on “How to create a custom login, logout and signup system in Django”. Put your questions in comments, we will be happy to answer you. Thank you!


Published : July 18, 2020