article

Sunday, June 5, 2022

Python Django Ajax Login Logout User Authentication

Python Django Ajax Login Logout User Authentication

Register App myapp and static file
 
//blogsite/settings.py
import os

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'myapp', #add myapp
]

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/4.0/howto/static-files/

STATIC_URL = 'static/'
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
STATICFILES_DIRS = (
    # location of your application, should not be public web accessible 
    './static',
)

LOGIN_REDIRECT_URL = '/'
LOGIN_URL = '/login'
Creating View
myapp/views.py
 
//myapp/views.py
from django.shortcuts import render, redirect
from django.http import HttpResponse
from django.contrib.auth import authenticate, login, logout
import json

context = {
    'page_title' : 'Blog Site'
}

# Create your views here.
def home(request):
    context['page_title'] = 'Home'
    return render(request, 'home.html',context)

def login_user(request):
    logout(request)
    resp = {"status":'failed','msg':''}
    username = ''
    password = ''
    if request.POST:
        username = request.POST['username']
        password = request.POST['password']

        user = authenticate(username=username, password=password)
        if user is not None:
            if user.is_active:
                login(request, user)
                resp['status']='success'
            else:
                resp['msg'] = "Incorrect username or password"
        else:
            resp['msg'] = "Incorrect username or password"
    return HttpResponse(json.dumps(resp),content_type='application/json')

#Logout
def logoutuser(request):
    logout(request)
    return redirect('/')
blogsite/urls.py
 
//blogsite/urls.py
from django.contrib import admin
from django.urls import include, path

from django.conf import settings
from django.conf.urls.static import static

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include('myapp.urls')),
] + static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT)
myapp/urls.py
 
//myapp/urls.py
from . import views
from django.contrib import admin
from django.urls import path, re_path
from django.contrib.auth import views as auth_views
from django.views.generic.base import RedirectView

urlpatterns = [
    path('redirect-admin', RedirectView.as_view(url="/admin"),name="redirect-admin"),
    path('', views.home, name="home-page"),
    path('login',auth_views.LoginView.as_view(template_name="login.html",redirect_authenticated_user = True),name='login'),
    path('userlogin', views.login_user, name="login-user"),
    path('logout',views.logoutuser,name='logout'),
]
myapp/templates/home.html
//myapp/templates/home.html
{% extends "base.html" %} 

{% block pageContent %}
<section class="text-center">
    <h4 class="mb-5"><strong>All Posts</strong></h4>
    <div class="row">
        <h1>Homepage - Python Django Ajax Login Logout User Authentication </h1>
    </div>
</section>
</div>  
{% endblock pageContent %}
myapp/templates/base.html
 
//myapp/templates/base.html
{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0"> 
    {% if page_title %}
    <title>{{ page_title }} | Blog Site</title>
    {% else %}
    <title>Blog Site</title>
    {% endif %}
    <link rel="stylesheet" href="{% static 'blogApp/assets/bootstrap/css/bootstrap.min.css' %}">

    <script src="https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js"></script>
</head>
<body>
    {% block TopNavigation %} {% include "TopNavigation.html" %} {% endblock TopNavigation %}
    <main class="my-5">
        <div class="container">
            {% block pageContent %} {% endblock pageContent %}
        </div>
    </main>
    {% block ScriptBlock %} {% endblock ScriptBlock %}
    <footer class="bg-light text-lg-start">
        <div class="text-center p-3" style="background-color: rgba(0, 0, 0, 0.2);">
            © {% now 'Y' %} Copyright:
            <a class="text-dark" href="#" target="_blank">Cairocoders</a>
        </div>
    </footer>

</body>
</html>
myapp/templates/login.html
//myapp/templates/login.html
{% extends 'base.html' %}

{% load static %}

{% block pageContent %}
<div class="row justify-content-center" style="margin-top: 150px;">
    <div class="col-lg-4 col-md-6 col-sm-12 col-xs-12">
        <p><img src="{{ MEDIA_URL}}/media/images/banner1.png" class="img-fluid" /></p>
        <div class="card card-default rounded-0 shadow">
            <div class="card-header">
                <h4 class="card-title"><b>Login</b></h4>
            </div>
            <div class="card-body">
                <div class="container-fluid">
                    <form id="login-user">
                        {% csrf_token %}
                        <div class="mdc-layout-grid">
                            <div class="mdc-layout-grid__inner">
                                <div class="form-group mb-3">
                                    <label for="username" class="control-label">Username</label>
                                    <input type="text" class="form-control rounded-0" name="username" id="username" required="required">
                                </div>
                                <div class="form-group mb-3">
                                    <label for="password" class="control-label">Password</label>
                                    <input type="password" class="form-control rounded-0" name="password" id="password" required="required">
                                </div>
                                <div class="form-group mb-3">
                                    <div class="d-flex w-100 justify-content-between align-items-center">
                                        <div class="col-md-4"><a href="#">Signup</a></div>
                                        <button class="btn btn-sm rounded-0 btn-primary">Login</button>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>
{% endblock pageContent %} 

{% block ScriptBlock %}
<script>
    $(function() {
        $('#login-user').submit(function(e) {
            e.preventDefault();
            var _this = $(this)
            $('.err-msg').remove();
            var el = $('<div>')
            el.addClass("alert alert-danger err-msg")
            el.hide()
            if (_this[0].checkValidity() == false) {
                _this[0].reportValidity();
                return false;
            }
            $.ajax({
                headers: {
                    "X-CSRFToken": '{{csrf_token}}'
                },
                url: "{% url 'login-user' %}",
                data: new FormData($(this)[0]),
                cache: false,
                contentType: false,
                processData: false,
                method: 'POST',
                type: 'POST',
                dataType: 'json',
                error: err => {
                    console.log(err)
                    alert_toast("An error occured", 'error');
                },
                success: function(resp) {
                    if (typeof resp == 'object' && resp.status == 'success') {
                        el.removeClass("alert alert-danger err-msg")
                        location.href = "{% url 'home-page' %}"
                    } else if (resp.status == 'failed' && !!resp.msg) {
                        el.text(resp.msg)
                    } else {
                        el.text("An error occured", 'error');
                        console.err(resp)
                    }
                    _this.prepend(el)
                    el.show('slow')
                }
            })
        })
    })
</script>
{% endblock ScriptBlock %}
myapp/templates/TopNavigation.html
 
//myapp/templates/TopNavigation.html
{% load static %}
<header>
    <nav class="navbar navbar-expand-lg navbar-light bg-white fixed-top">
        <div class="container">
            <a class="navbar-brand" target="_blank" href="#">Cairocoders</a>
            <button class="navbar-toggler" type="button" data-mdb-toggle="collapse" data-mdb-target="#navbarExample01" aria-controls="navbarExample01" aria-expanded="false" aria-label="Toggle navigation">
            <i class="fas fa-bars"></i>
            </button>
            <div class="collapse navbar-collapse" id="navbarExample01">
                <ul class="navbar-nav me-auto mb-2 mb-lg-0">
                    <li class="nav-item active">
                        <a class="nav-link" aria-current="page" href="{% url 'home-page' %}">Home</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="#">All Categories</a>
                    </li>
                </ul>

                <ul class="navbar-nav d-flex flex-row">
                    {% if user.id %}
                    <li class="nav-item me-3 me-lg-0">
                        <a class="nav-link" href="#">
                            Hello, {{ user.first_name }} {{user.last_name}}
                        </a>
                    </li>
                    <li class="nav-item me-3 me-lg-0">
                        <a class="nav-link" href="{% url 'logout' %}">Logout</a>
                    </li>
                    {% else %}
                    <li class="nav-item me-3 me-lg-0">
                        <a class="nav-link" href="{% url 'login' %}">Login</a>
                    </li>
                    {% endif %}
                </ul>
            </div>
        </div>
    </nav>
</header>
Run : C:\django\blogsite>python manage.py runserver

Related Post