You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Django实现首页按登录状态跳转:未登录转登录页,已登录转用户页

解决方案

1. 编写首页跳转视图

新增一个处理首页/跳转逻辑的视图,判断用户登录状态后重定向到对应页面,推荐用简洁的函数视图:

# 在项目根目录的views.py(或指定视图文件)中添加
from django.shortcuts import redirect

def index(request):
    if request.user.is_authenticated:
        # 已登录用户跳转到个人首页,用URL名称反向解析更可靠
        return redirect('home', username=request.user.username)
    else:
        # 未登录用户跳转到登录页
        return redirect('login')

如果偏好类视图,也可以用RedirectView实现:

from django.views.generic.base import RedirectView

class IndexRedirectView(RedirectView):
    def get_redirect_url(self, *args, **kwargs):
        if self.request.user.is_authenticated:
            return f'/{self.request.user.username}/'
        else:
            return '/accounts/login/'

2. 配置根URL路由

在项目根目录的urls.py中,将首页路由指向刚才编写的视图:

from django.contrib import admin
from django.urls import path, include
from .views import index  # 若用类视图则导入IndexRedirectView

urlpatterns = [
    path('', index, name='index'),  # 首页核心路由
    path('admin/', admin.site.urls),
    path('accounts/login/', LoginView.as_view(redirect_authenticated_user=True, template_name='users/login.html'), name='login'),
    path('', include('your_app_name.urls')),  # 替换为你的应用名称
]

如果使用类视图,替换为:

path('', IndexRedirectView.as_view(), name='index'),

3. 优化现有代码(可选)

  • 自定义LoginView的template_name在类中已定义,可移除URL配置里的重复定义,保持代码一致:
    path('accounts/login/', LoginView.as_view(redirect_authenticated_user=True), name='login'),
    
  • 视图类名遵循Django规范,建议将home改为Home:
    class Home(LoginRequiredMixin, ListView):
        model = Item
        template_name = 'app/home.html'
        context_object_name = 'items'
    
    同时更新应用URL配置:
    path('<str:username>/', Home.as_view(), name='home'),
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 00:45:37