Custom Login System in Django python

Custom Login System in Django python

Step 1. First, create a new Django project if you haven't already:

python manage.py startapp adminpanel
Step 2. Update Settings.py
MIDDLEWARE = [
    # ...
    'adminpanel.middleware.AuthRequiredMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    # ...
]

# Add these if not present
AUTHENTICATION_BACKENDS = [
    'django.contrib.auth.backends.ModelBackend',
]

LOGIN_URL = 'login'
LOGIN_REDIRECT_URL = 'dashboard'

Step 3. Create URLs In adminpanel/urls.py:

from django.urls import path
from . import views

urlpatterns = [
    path('login/', views.custom_login, name='login'),
    path('dashboardview/', views.dashboardview, name='dashboardview'),
    path('logout/', views.custom_logout, name='logout'),
]

Step 4. Include adminpanel/urls.py in main urls.py

from django.urls import path,include 

urlpatterns = [

   // other urls

    path('adminpanel/', include('adminpanel.urls')),
]

Step 4. Create Views In adminpanel/views.py

from django.shortcuts import render, redirect
from django.contrib.auth import authenticate, login
from django.contrib import messages
from django.views.decorators.csrf import csrf_exempt
from django.contrib.auth import logout

@csrf_exempt  # Only for development, remove in production
def custom_login(request):
    if request.method == 'POST':
        username = request.POST.get('username')
        password = request.POST.get('password')
        
        user = authenticate(request, username=username, password=password)
        
        if user is not None:
            login(request, user)
            return redirect('dashboardview')  # Fixed name
        else:
            messages.error(request, 'Invalid credentials')
    
    return render(request, 'adminpanel/templates/login.html')

def dashboardview(request):
    return render(request, 'adminpanel/templates/dashboard/index.html')

def custom_logout(request):
    logout(request)
    return redirect('login')

Step 5. Create adminpanel/middleware.py file

from django.shortcuts import redirect
from django.urls import reverse

class AuthRequiredMiddleware:
    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        # List of paths that don't require authentication
        exempt_paths = [
            reverse('login'),
            # Add other exempt paths here
        ]
        
        if not request.user.is_authenticated and request.path not in exempt_paths:
            return redirect('login')
        
        response = self.get_response(request)
        return response

Step 6: make templates folder and make login.html file inside templates folder

<!DOCTYPE html>
<html>
<head>
    <title>Custom Login</title>
    <style>
        .login-form {
            max-width: 400px;
            margin: 50px auto;
            padding: 20px;
            border: 1px solid #ddd;
            border-radius: 5px;
        }
        .form-group {
            margin-bottom: 15px;
        }
        .error {
            color: red;
        }
    </style>
</head>
<body>
    <div class="login-form">
        <h2>Login</h2>
        
        {% if messages %}
            {% for message in messages %}
                <div class="error">{{ message }}</div>
            {% endfor %}
        {% endif %}
        
        <form method="post">
            {% csrf_token %}
            
            <div class="form-group">
                <label for="username">Username</label>
                <input type="text" id="username" name="username" required>
            </div>
            
            <div class="form-group">
                <label for="password">Password</label>
                <input type="password" id="password" name="password" required>
            </div>
            
            <button type="submit">Login</button>
        </form>
    </div>
</body>
</html>

Step 7. make dashboard folder in template folder and make index.html file inside dashboard folder

templates/dashboard/index.html

<!DOCTYPE html>
<html>
<head>
    <title>Dashboard</title>
</head>
<body>
    <h1>Welcome to Your Dashboard, {{ request.user.username }}!</h1>
    <p>This is your protected dashboard page.</p>
    <a href="{% url 'logout' %}">Logout</a>
</body>
</html>

0 Comments

Leave a Reply

You must be logged in to post a comment.