You need to enable JavaScript to run this app. 使用django-user-accounts时如何让已登录用户从登录URL重定向到首页
优惠活动
大模型
产品
解决方案
定价
更多

使用django-user-accounts时如何让已登录用户从登录URL重定向到首页

解决方案

你可以通过两种适配django-user-accounts的方案实现需求,不需要大幅修改现有配置:

方法1:重写登录路由配置(推荐,无需修改源码)

django-user-accounts自带的LoginView原生支持已登录用户跳转参数,只需要在你的urls.py中覆盖默认的登录路由规则即可:

from account.views import LoginView
# 其余原有导入保持不变

urlpatterns = [
    # 把重写的登录路由放在引入account.urls之前,保证优先级更高
    path('accounts/login/', LoginView.as_view(authenticated_redirect='index'), name='account_login'),
    path('accounts/', include('account.urls')),
    # 你的原有路由保持不变
    path('', index, name='index'),
    path('news-feed/', PostListView.as_view(), name='home2'),
]

其中authenticated_redirect参数填写你要跳转的目标路由名,示例中填index即跳转到你的站点首页,如果要跳转到信息流页则填home2即可。

方法2:自定义登录视图校验(适用于你已经重写了登录视图的场景)

如果你的登录逻辑是自定义的,直接给视图加登录状态校验装饰器即可:

  • 函数视图配置:
from django.contrib.auth.decorators import user_passes_test

@user_passes_test(lambda u: u.is_anonymous, login_url=None)
def your_custom_login(request):
    # 原有登录逻辑保持不变
    ...
  • 类视图配置:
from django.contrib.auth.decorators import user_passes_test
from django.utils.decorators import method_decorator

@method_decorator(user_passes_test(lambda u: u.is_anonymous, login_url=None), name='get')
class YourCustomLoginView(View):
    # 原有登录逻辑保持不变
    ...

配置完成后已登录用户访问登录页时,会自动跳转到settings.py中配置的LOGIN_REDIRECT_URL,你可以根据需要修改该配置:

# settings.py修改,跳站点首页
LOGIN_REDIRECT_URL = '/'

补充配置优化

建议你把现有settings.py中的LOGIN_URL改为带开头斜杠的绝对路径,避免相对路径跳转异常:

LOGIN_URL = '/accounts/login/'

内容的提问来源于stack exchange,提问作者sly_Chandan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.17 00:24:02