Django类视图登录成功后出现404,无法跳转至个人主页
Django登录成功后跳转至自定义个人主页的解决方案
问题背景
将博客登录功能改为Django类视图authorlogin,个人主页保留函数视图authorprofile。登录成功后页面自动跳转到http://127.0.0.1:8000/accounts/profile/,触发404错误——该路径未匹配项目现有URL规则。现有URL配置:
- 主
urls.py包含author/路径,关联author应用的URL配置 author应用的urls.py中,登录路径为author.login/(name='login'),个人主页路径为profile(name='profile')
需求:登录成功后直接跳转至个人主页,而非默认错误路径。
问题原因
Django内置LoginView默认登录成功后,优先读取settings.LOGIN_REDIRECT_URL配置的跳转路径;若未配置该参数,则使用默认路径/accounts/profile/。你的项目未配置LOGIN_REDIRECT_URL,也未定义/accounts/profile/对应的URL规则,因此触发404错误。
两种解决方法
方法一:在settings.py中配置全局跳转路径
在项目settings.py末尾添加配置,指定登录成功后的跳转目标为个人主页的命名URL:
# 直接使用个人主页的命名URL(需确保author.urls中profile的name='profile') LOGIN_REDIRECT_URL = 'profile' # 若后续为author应用添加命名空间,可改为: # LOGIN_REDIRECT_URL = 'author:profile' # 此时需修改主urls.py的include语句,添加命名空间: # path('author/', include(('author.urls', 'author'), namespace='author'))
方法二:在类视图中重写get_success_url方法
直接在authorlogin类视图中重写get_success_url方法,指定跳转路径:
from django.urls import reverse class authorlogin(LoginView): template_name='login.html' def form_valid(self, form): # 补充:格式化显示用户名 messages.success(self.request, f'Welcome mr.{form.get_user().username}') return super().form_valid(form) def form_invalid(self, form): # 补充:登录失败应使用error类型消息 messages.error(self.request,'Logged in information incorrect') return super().form_invalid(form) def get_context_data(self, **kwargs) : context=super().get_context_data(**kwargs) context['type']='login' return context # 重写方法指定登录成功后的跳转路径 def get_success_url(self): # 使用命名URL跳转至个人主页 return reverse('profile') # 若有命名空间则改为:return reverse('author:profile')
额外优化建议
author应用的urls.py中,个人主页路径建议添加末尾斜杠,符合Django URL规范:path('profile/', views.authorprofile, name='profile')authorprofile函数视图中,@login_required装饰器已自动校验用户登录状态,内部的if request.user.is_authenticated判断可省略,简化代码:@login_required def authorprofile(request): data = Post.objects.filter(author=request.user) return render(request, 'profile.html', {'data': data})
内容的提问来源于stack exchange,提问作者Abrar Rofique
相关产品推荐
相关产品推荐

