DEV Community

Cover image for Django login & logout using Sessions
Madhuban Khatri
Madhuban Khatri

Posted on

10 2

Django login & logout using Sessions

Hi Everyone,
In this post, I m showing to you how to use Django Sessions for Login and Logout.

First of all you have to create project dj_admin and then startapp app1. After this you have to add app1 in settings INSTALLED_APPS. Then include apps urls in main project urls.

views.py

from django.shortcuts import render, redirect
from django.http import HttpResponse
from .models import User


# Create your views here.
def home(request):
    if 'user' in request.session:
        current_user = request.session['user']
        param = {'current_user': current_user}
        return render(request, 'base.html', param)
    else:
        return redirect('login')
    return render(request, 'login.html')



def signup(request):
    if request.method == 'POST':
        uname = request.POST.get('uname')
        pwd = request.POST.get('pwd')
        # print(uname, pwd)
        if User.objects.filter(username=uname).count()>0:
            return HttpResponse('Username already exists.')
        else:
            user = User(username=uname, password=pwd)
            user.save()
            return redirect('login')
    else:
        return render(request, 'signup.html')



def login(request):
    if request.method == 'POST':
        uname = request.POST.get('uname')
        pwd = request.POST.get('pwd')

        check_user = User.objects.filter(username=uname, password=pwd)
        if check_user:
            request.session['user'] = uname
            return redirect('home')
        else:
            return HttpResponse('Please enter valid Username or Password.')

    return render(request, 'login.html')


def logout(request):
    try:
        del request.session['user']
    except:
        return redirect('login')
    return redirect('login')

Enter fullscreen mode Exit fullscreen mode

urls.py

from django.urls import path
from . import views

urlpatterns = [
    path('', views.home, name='home'),
    path('login/', views.login, name='login'),
    path('logout/', views.logout, name='logout'),
    path('signup/', views.signup, name='signup'),
]
Enter fullscreen mode Exit fullscreen mode

models.py

from django.db import models

# Create your models here.
class User(models.Model):
    username = models.CharField(max_length=30)
    password = models.CharField(max_length=50)

    def __str__(self):
        return self.username

Enter fullscreen mode Exit fullscreen mode

Code in Templates

1.) create base.html

<!DOCTYPE html>
<html>
<head>
    <title>{% block title %}{% endblock %}</title>
</head>
<body>
    <h1>My Site</h1>

    <a href="/">Home</a>
    <span>/</span>

    {% if current_user %}
        <a href="{% url 'logout' %}">Logout</a>
        <hr>
        <h2>Welcome <span style="color: dodgerblue;">{{current_user}}</span>!</h2>
    {% else %}
        <a href="{% url 'login' %}">Login</a>
        <span>/</span>
        <a href="{% url 'signup' %}">Sign Up</a>
        <hr>
        <h2>Login to access this website!</h2>
    {% endif %}


    {% block body %}{% endblock %}
</body>
</html>
Enter fullscreen mode Exit fullscreen mode

2. create login.html

{% extends 'base.html' %}
{% block title %}Login{% endblock %}

{% block body %}
    <h2>Login</h2>

    <form method="POST">
        {% csrf_token %}
        <input type="text" name="uname" placeholder="User Name">
        <br><br>
        <input type="text" name="pwd" placeholder="Password">
        <br><br>
        <input type="submit" name="submit" value="Login">
    </form>


{% endblock %}
Enter fullscreen mode Exit fullscreen mode

3. create signup.html

{% extends 'base.html' %}
{% block title %}Sing Up{% endblock %}

{% block body %}
    <h2>Sign Up</h2>

    <form method="POST">
        {% csrf_token %}
        <input type="text" name="uname" placeholder="Username">
        <br><br>
        <input type="text" name="pwd" placeholder="Password">
        <br><br>
        <input type="submit" name="submit" value="Sign Up">
    </form>

{% endblock %}
Enter fullscreen mode Exit fullscreen mode

Or you can check my GitHub Profile using this Link

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more