35. User login process

Now, we will implement the user login functionality.

First, we will rename the login view function to perform_login for better organization, as this function will handle the login process directly.

views.py
def perform_login(request): 
    return render(request, 'user/login.html') 

Next, we need to import the necessary Django packages at the top of the views.py file to enable login functionality.

views.py
from django.contrib.auth import login, logout, authenticate

Note: It is highly recommended to rename the login view function to perform_login to avoid naming conflicts, as we will be importing another function called login from Django's authentication module.

Also, remember to update the function name in the urlpatterns list of the urls.py file (inside the store folder). Additionally, change its reference in the navbar.html file and the create_account.html file.

path('perform_login/', perform_login, name="perform_login"), 

Now, inside the login.html file, add an action attribute to the form, linking it to the perform_login view URL. This will allow us to process the login system within our function using the data obtained from the request.

login.html
<form method="POST" action="{% url 'perform_login' %}">

Now, we will edit the perform_login function to implement the login functionality:

views.py
def perform_login(request):
    error = False
    if request.user.is_authenticated :
        return redirect('store')
    if request.method == "POST":
        data = request.POST.dict()
        if "email" in data and "password" in data :
            email = data.get("email")
            password = data.get("password")
            user = authenticate(request, username=email, password=password) #? authenticating the user
            if user :
                #? perform login
                login(request, user)
                return redirect('store')
            else :
                error = True
        else :
            error = True
    
    context = {"error" : error}
    return render(request, 'user/login.html', context)

The changes made were:

  • Function Definition: perform_login(request)

    • Handles login logic for a user request.

  • Variable Initialization: error = False

    • Initializes an error flag to track login issues.

  • Authenticated Check: if request.user.is_authenticated

    • Redirects to 'store' if the user is already authenticated.

  • POST Request Check: if request.method == "POST"

    • Processes the form data if the request method is POST.

  • Data Extraction: data = request.POST.dict()

    • Converts POST data to a dictionary for easy access.

  • Email and Password Validation: if "email" in data and "password" in data

    • Checks if both email and password are provided in the form data.

  • Extract Email and Password:

    • email = data.get("email")

    • password = data.get("password")

    • Retrieves email and password from the form data.

  • User Authentication: user = authenticate(request, username=email, password=password)

    • Authenticates the user using the provided email and password (Note: Django performs the authentication using the username).

  • Successful Authentication Check: if user

    • Checks if the authentication was successful.

  • Login and Redirect:

    • login(request, user)

    • return redirect('store')

    • Logs the user in and redirects to 'store' if authentication succeeds.

  • Error Handling:

    • error = True if authentication fails or if email/password are missing.

  • Context Preparation: context = {"error" : error}

    • Prepares context data with the error flag for the template.

  • Render Login Template: return render(request, 'user/login.html', context)

    • Renders the login template with the context data.

Lastly, to display the error message, reference the 'error' context variable from the perform_login function in the views.py file within the login.html file.

Now, when accessing the page as an anonymous user, you can click the login button and log in using the admin email and password (the only client currently created). If the email or password is incorrect, an error message will be displayed, prompting the user to re-enter their credentials.

User provides wrong email or password

Last updated