我有一个带有
auth
库的 django-allauth
系统,并且我实现了一些登录、注销功能,并且工作正常。但我想自己实现一个个人资料页面。有了这个,我对 Django 重定向感到非常困惑。
我有一个名为
HomeRequestHandler
的基于类的视图,它继承了 LoginRequiredMixin
:
from django.contrib.auth.mixins import LoginRequiredMixin
from django.views.generic import TemplateView
class HomeRequestHandler(LoginRequiredMixin, TemplateView):
template_name = "home.html"
在我的网址中我只是将其称为“”:
from django.views.generic import TemplateView
from django.urls import path
from . import views
urlpatterns = [
path("", views.HomeRequestHandler.as_view(), name="home"),
path("profile/", TemplateView.as_view(template_name="account/profile.html"), name="profile"),
]
在我的
settings.py
中,我有一个常数LOGIN_REDIRECT_URL
:
LOGIN_REDIRECT_URL = reverse_lazy('profile')
当我尝试登录时,即使定义了
LOGIN_REDIRECT_URL
,我也会被重定向到“/”。但如果我改变我的观点中的一件事:
from django.contrib.auth.mixins import LoginRequiredMixin
from django.views.generic import TemplateView
class HomeRequestHandler(LoginRequiredMixin, TemplateView):
template_name = "home.html"
redirect_field_name = "redirect_to"
它将我的网址
http://localhost:8000/accounts/login/?next=/
更改为http://localhost:8000/accounts/login/?redirect_to=/
,现在常量正常工作,为什么???
在Django中默认情况下,
LoginRequiredMixin
使用?next=
参数在登录后重定向。当 Django 将未经身份验证的用户重定向到登录页面时,此参数会自动附加到 URL。 参考。
您已在
LOGIN_REDIRECT_URL = reverse_lazy('profile')
文件中设置了 settings.py
,该文件应该在登录后将用户重定向到个人资料页面,但此设置仅在 URL 中不存在 ?next=
参数或用户登录时使用直接从登录页面访问,无需从其他受保护页面重定向。
当您修改
HomeRequestHandler
类以包含 redirect_field_name = "redirect_to"
时,您实质上更改了 LoginRequiredMixin
查找的查询参数。现在,它不再使用 next
,而是查找 redirect_to
。因此,当 Django 找不到 redirect_to
参数(因为这不是默认行为)时,它会转而使用 LOGIN_REDIRECT_URL
设置。