Login and Logout Functionality in Django

  • Sure! Here's an example code to implement login and logout functionality using Django and an HTML template:
  • urls.py


    from django.urls import path
    from . import views
    from django.views.generic import TemplateView

    urlpatterns = [
        path('', views.handleLoginForm),
        path('login', views.handleLogin),
        path('welcome', views.handleWelcome),
        path('logout', views.handleLogout),
        path('public', TemplateView.as_view(template_name='public.html'))
    ]

  • views.py


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

    def handleLoginForm(request):
        if request.user.is_authenticated:
            return redirect("/public")
        return render(request, "login.html")

    def handleLogin(request):
        if request.method == 'POST':
            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('/welcome')
            else:
                error_message = "Invalid username or password"
                return render(request, 'login.html', {'error_message': error_message})

        return redirect("/")

    def handleWelcome(request):
        if request.user.is_authenticated:
            return render(request, "welcome.html")
        return redirect("/")

    def handleLogout(request):
        if request.user.is_authenticated:
            logout(request)
        return redirect("/")

  • base.html


    <!DOCTYPE html>
    <html lang="en">

    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet"
            integrity="sha384-9ndCyUaIbzAi2FUVXJi0CjmCapSmO7SnpJef0486qhLnuZ2cdeRhO02iuK6FUUVM" crossorigin="anonymous">
        <title>Document</title>
    </head>

    <body>
        <div class="container h4">
            {{user.username}}
        </div>
        {% block content %}

        {% endblock content %}
        <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"
            integrity="sha384-geWF76RCwLtnZ8qwWowPQNguL3RmwHVBC9FhGdlKrxdiJJigb/j/68SIy3Te4Bkz"
            crossorigin="anonymous"></script>

    </body>

    </html>

  • login.html


    {% extends "base.html" %}

    {% block content %}
    <div class="container">
        <div class="my-4 h4 text-center text-underline">
            <p>
                <u>
                    Login
                </u>
            </p>
        </div>
        <div class="my-1">
            {% if error_message %}
            <p>{{ error_message }}</p>
            {% endif %}
        </div>
        <form action="/login" method="post">
            {% csrf_token %}
            <div class="mb-3">
                <label for="username" class="form-label">Username</label>
                <input type="text" class="form-control" name="username" id="username" required placeholder="Enter Username">
            </div>
            <div class="mb-3">
                <label for="password" class="form-label">Password</label>
                <input class="form-control" name="password" id="password" required placeholder="Enter Password"
                    type="password">
            </div>
            <button type="submit" class="btn btn-primary">Login</button>
        </form>
    </div>
    {% endblock content %}

  • welcome.html


    {% extends "base.html" %}

    {% block content %}
    <div class="container m-5">
        <div class="h4">
            Welcome! You have logged in successfully.
        </div>
        <div class="my-2">
            <a href="/logout" class="btn btn-primary btn-sm"> Logout</a>
        </div>
    </div>

    {% endblock content %}

  • public.html


    {% extends "base.html" %}

    {% block content %}
    <div class="container">
        <h1>
            This is public content
        </h1>
        <div>
            Lorem ipsum dolor sit amet consectetur adipisicing elit. Aut tenetur laudantium aliquam illum fuga aspernatur
            quis animi porro ratione, nesciunt error ipsam commodi, qui temporibus possimus aperiam accusamus. Maxime
            tempora deleniti modi rem, omnis reprehenderit ducimus quia ab. Ratione libero quasi qui odit vel excepturi
            suscipit recusandae numquam totam nisi. Ipsum repellat consequuntur iste ab cupiditate. Magnam delectus quo
            corporis aperiam veniam unde commodi pariatur repudiandae facere deleniti sapiente facilis provident sed illo
            cumque temporibus maxime, laboriosam tempore accusantium ducimus dolorum explicabo in! Repellat maxime sit quia
            tenetur a laborum animi blanditiis cumque eius, voluptatum perspiciatis aperiam necessitatibus, consequatur
            facilis.
        </div>
        {% if user.is_authenticated %}
        <div class="my-2">
            <a href="/logout" class="btn btn-primary btn-sm"> Logout</a>
        </div>
        {% else %}
        <a href="/" class="btn btn-primary btn-sm"> Login</a>
        {% endif %}
    </div>
    {% endblock content %}

  • In Django views, you can check whether a user is authenticated or not using the request.user.is_authenticated attribute. It returns True if the user is authenticated, and False otherwise.
  • If the user is not authenticated, you can perform the appropriate actions, such as redirecting them to the login page.
  • You can use this check within any view function to control the behavior based on the user's authentication status.
  • To use this code, you need to make sure you have Django installed and configured properly. Additionally, you will need to create the necessary templates and include the required URL mappings in your main `urls.py` file. This example code provides a basic implementation of login and logout functionality, and you can customize it further based on your specific requirements.
  • This example also include in gothub repo:
  • In Django, you can access the current user information using the request.user object within views or templates. This object represents the user making the current request.
  • Once a user is authenticated, you can access their information through the request.user object. For example, you can get the username, email, or any other fields defined in your user model.

    def profile_view(request):
        user = request.user
        username = user.username
        email = user.email
        # Access other user fields


No comments:

Post a Comment