部署在Ubuntu服务器上的Django应用程序登录成功后重定向到登录页面

问题描述 投票:0回答:1

我已经在 ubuntu 22 服务器上部署了 django,并使用 nginx 作为应用程序服务器,但是当我登录系统并在每个请求上时,我都会被重定向回登录名。`

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`

类 SalesListView(ListView): ”“” 用于显示销售交易的视图。

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)

这就是我从请求中获取用户信息的方式。`

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"

这是我的缓存设置

如何解决会话错误

django nginx ubuntu-22.04
1个回答
0
投票

从您的代码来看,在我看来,好像您没有在会话中保存身份验证。因此身份验证可能有效,但在以下视图中无法访问。用户被重定向到没有用户信息的

SalesListView
,然后又重定向回登录视图。

除非您有充分的理由,否则我不建议您编写自己的登录代码,因为它与安全性高度相关。相反,依赖 Django 提供的 LoginView。然后您可以像从 request.user 中一样访问该用户。 https://docs.djangoproject.com/en/5.1/topics/auth/default/#django.contrib.auth.views.LoginView

© www.soinside.com 2019 - 2024. All rights reserved.