Django application deployed on Ubuntu server redirects to login page after successful login

I have deployed django on ubuntu 22 server with nginx as the application server, but when I login in to the system and on each request I get redirected back to the login.`

if form.is_valid():
    username = form.cleaned_data.get("username")
    password = form.cleaned_data.get("password")
    logger.debug(f"Attempting to authenticate user {username}.")
    user = authenticate(username=username, password=password)

    if user is not None:
        logger.debug(f"Authenticated user {username}.")
        login(request, user)
        if user.role == 'STAFF':
            return redirect("sales:sales_list")
        elif user.role in ["MANAGER", "SUPERVISOR",]:
            return redirect("authentication:manager_dashboard")
        elif user.role in ["ADMIN", "GENERAL", "CEO"]:
            return redirect('master:index')

this is how I did the authentication`

class SalesListView(ListView): """ View for displaying sales transactions.

Requires user to be logged in and have specific roles (STAFF, MANAGER, ADMIN, SUPERVISOR, CEO).
Displays sales data based on user role and branch.
"""

template_name = "manager/purchase/sales.html"
model = Sale
context_object_name = "sales"

def dispatch(self, request, *args, **kwargs):
    """
    Custom dispatch method to handle role-based template selection.

    Sets different template names based on the user's role.
    """
    user = request.user

    if not user.is_authenticated:
        # If not authenticated, redirect to login page
        messages.error(request, 'You need to log in first!', extra_tags="danger")
        return redirect('authentication:login')

    self.branch = user.branch.id
    self.user_role = user.role

    print(f"User branch {self.branch} : user role {self.user_role}")

    if self.user_role == 'STAFF':
        self.template_name = 'team_member/sales/sales.html'  # Set template for staff role
    # TODO: Add logic for other roles and master view

    return super().dispatch(request, *args, **kwargs)

this is how I get user information from the request.`

SESSION_COOKIE_AGE = 7200 SESSION_EXPIRE_AT_BROWSER_CLOSE = False SECURE_HSTS_SECONDS = 31536000

CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.locmem.LocMemCache', 'LOCATION': 'unique-snowflake', 'TIMEOUT': 300, 'OPTIONS': { 'MAX_ENTRIES': 1000, 'CULL_FREQUENCY': 3, } } }

Session Engine

SESSION_ENGINE = "django.contrib.sessions.backends.cache" SESSION_CACHE_ALIAS = "default"

this is my cache settings

How to resolve the session error

From your code, it looks to me, as if your are not saving the authentication in the session. So the authentication probably works, but is not accessible in following views. The user is redirected to the SalesListView which does not have the user information and then in turn redirects back to the login view.

Unless you have good reasons for it, I would not recommend writing your own login code, as it is highly security relevant. Instead, rely on the LoginView provided by Django. You can then access the user like you did from request.user. https://docs.djangoproject.com/en/5.1/topics/auth/default/#django.contrib.auth.views.LoginView

Back to Top