User Auth

  • Step

    1 Create the Django project and app by using the below command

    
                        django-admin startproject core
                        cd core
                        python manage.py startapp authentication
    
                        

    2. Register app name 'authentication' in Installed_Apps in settings.py file.

    
                        INSTALLED_APPS = [
                            "django.contrib.admin",
                            "django.contrib.auth",
                            "django.contrib.contenttypes",
                            "django.contrib.sessions",
                            "django.contrib.messages",
                            "django.contrib.staticfiles",
                            "authentication", // App name 
                        ]
    
                        

    3. in authentication/view.py

    
    
    # Import necessary modules and models
    from django.shortcuts import render, redirect
    from django.contrib import messages
    from django.contrib.auth import authenticate, login
    from django.contrib.auth.decorators import login_required
    from django.contrib.auth.models import User
    from .models import *
    
    # Define a view function for the home page
    def home(request):
        return render(request, 'home.html')
    
    # Define a view function for the login page
    def login_page(request):
        # Check if the HTTP request method is POST (form submission)
        if request.method == "POST":
            username = request.POST.get('username')
            password = request.POST.get('password')
            
            # Check if a user with the provided username exists
            if not User.objects.filter(username=username).exists():
                # Display an error message if the username does not exist
                messages.error(request, 'Invalid Username')
                return redirect('/login/')
            
            # Authenticate the user with the provided username and password
            user = authenticate(username=username, password=password)
            
            if user is None:
                # Display an error message if authentication fails (invalid password)
                messages.error(request, "Invalid Password")
                return redirect('/login/')
            else:
                # Log in the user and redirect to the home page upon successful login
                login(request, user)
                return redirect('/home/')
        
        # Render the login page template (GET request)
        return render(request, 'login.html')
    
    # Define a view function for the registration page
    def register_page(request):
        # Check if the HTTP request method is POST (form submission)
        if request.method == 'POST':
            first_name = request.POST.get('first_name')
            last_name = request.POST.get('last_name')
            username = request.POST.get('username')
            password = request.POST.get('password')
            
            # Check if a user with the provided username already exists
            user = User.objects.filter(username=username)
            
            if user.exists():
                # Display an information message if the username is taken
                messages.info(request, "Username already taken!")
                return redirect('/register/')
            
            # Create a new User object with the provided information
            user = User.objects.create_user(
                first_name=first_name,
                last_name=last_name,
                username=username
            )
            
            # Set the user's password and save the user object
            user.set_password(password)
            user.save()
            
            # Display an information message indicating successful account creation
            messages.info(request, "Account created Successfully!")
            return redirect('/register/')
        
        # Render the registration page template (GET request)
        return render(request, 'register.html')
    
    
            

    4. in authentication/models.py

    
            from django.db import models
            from django.contrib.auth.models import User
    
            

    5. update database configuration in setting.py

    6. migrate models

    
            python manage.py makemigrations
            python manage.py migrate 
            

    7. create the super user by using below write command

    
            python manage.py createsuperuser 
            

    8. url

    
            # Import necessary modules
          from django.contrib import admin  # Django admin module
          from django.urls import path       # URL routing
          from authentication.views import *  # Import views from the authentication app
          from django.conf import settings   # Application settings
          from django.contrib.staticfiles.urls import staticfiles_urlpatterns  # Static files serving
    
          # Define URL patterns
          urlpatterns = [
              path('home/', home, name="recipes"),      # Home page
              path("admin/", admin.site.urls),          # Admin interface
              path('login/', login_page, name='login_page'),    # Login page
              path('register/', register_page, name='register'),  # Registration page
          ]
    
       
    
          

    9. authentication/templates/login.html

    
    
          <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Login</title>
        <link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" rel="stylesheet">
    </head>
    <body>
        <div class="container mt-5">
            <!-- Login form -->
            <form class="col-6 mx-auto card p-3 shadow-lg" method="post" enctype="multipart/form-data">
                <h1 style="text-align: center;"><span style="color: green;">GeeksforGeeks</span></h1>
    
                {% csrf_token %}  <!-- CSRF token for security -->
    
                <!-- Login heading -->
                <h3>Login</h3>
                <hr>
    
                <!-- Display error/success messages -->
                {% if messages %}
                <div class="alert alert-primary" role="alert">
                    {% for message in messages %}
                    {{ message }}
                    {% endfor %}
                </div>
                {% endif %}
    
                <!-- Username input field -->
                <div class="form-group">
                    <label for="exampleInputEmail1">Username</label>
                    <input type="text" class="form-control" name="username" id="exampleInputEmail1" aria-describedby="emailHelp"
                        placeholder="Enter username" required>
                </div>
    
                <!-- Password input field -->
                <div class="form-group">
                    <label for="exampleInputPassword1">Password</label>
                    <input type="password" name="password" class="form-control" id="exampleInputPassword1" placeholder="Password" required>
                </div>
    
                <!-- Link to registration page -->
                <p>Don't have an account <a href="/register/">Register</a> </p>
    
                <!-- Submit button -->
                <button type="submit" class="btn btn-primary">Submit</button>
            </form>
        </div>
    </body>
    </html>
    
          

    10. authentication/templates/register.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://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" rel="stylesheet">
        <title>Registration Form</title>
    </head>
    <body>
        <div class="container mt-5">
            <!-- Registration form -->
            <form class="col-6 mx-auto card p-3 shadow-lg" method="post" enctype="multipart/form-data">
                {% csrf_token %}  <!-- CSRF token for security -->
    
                <!-- Registration form heading -->
                <h1 style="text-align: center;"><span style="color: green;">GeeksforGeeks</span></h1>
                <h3>Register</h3>
                <hr>
    
                <!-- Display error/success messages -->
                {% if messages %}
                <div class="alert alert-primary" role="alert">
                    {% for message in messages %}
                    { { message }}
                    {% endfor %}
                </div>
                {% endif %}
    
                <!-- First Name input field -->
                <div class="form-group">
                    <label for="exampleInputEmail1">First name</label>
                    <input type="text" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp"
                        placeholder="Enter First name" name="first_name" required>
                </div>
    
                <!-- Last Name input field -->
                <div class="form-group">
                    <label for="exampleInputEmail1">Last name</label>
                    <input type="text" name="last_name" class="form-control" id="exampleInputEmail1"
                        aria-describedby="emailHelp" placeholder="Enter Last name" required>
                </div>
    
                <!-- Username input field -->
                <div class="form-group">
                    <label for="exampleInputEmail1">Username</label>
                    <input type="text" class="form-control" name="username" id="exampleInputEmail1"
                        aria-describedby="emailHelp" placeholder="Enter email" required>
                </div>
    
                <!-- Password input field -->
                <div class="form-group">
                    <label for="exampleInputPassword1">Password</label>
                    <input type="password" class="form-control" name="password" id="exampleInputPassword1"
                        placeholder="Password" required>
                </div>
    
                <!-- Link to login page for users who already have an account -->
                <p>Already have an account <a href="/login/">Login</a> </p>
    
                <!-- Submit button -->
                <button type="submit" class="btn btn-primary">Submit</button>
            </form>
        </div>
    </body>
    </html>
    
          

    11. authentication/templates/home.html

    
    
          <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title style="color: green;">Welcome to Geeksforgeeks ????</title>
        <style>
            .container {
                text-align: center;
                margin: 100px auto;
                max-width: 500px;
                padding: 20px;
                background-color: #fff;
                border-radius: 10px;
                box-shadow: 0 0 10px rgba(0, 0, 0, 0.2);
            }
    
            h1 {
                color: green;
                font-weight: bold;
            }
    
            img {
                width: 60%;
            }
        </style>
    </head>
    <body>
        <div class="container">
            <!-- Page heading -->
            <h1>Welcome to Geeksforgeeks ????</h1>
            
            <!-- Animated GIF -->
            <!-- Use "welcome.gif" as the source for the GIF -->
            <img src="https://i.ibb.co/RNB6jpM/welcome.gif" alt="Welcome Cartoon">
        </div>
    </body>
    </html>
    
          

    12. run

    
          python manage.py runserver