我的登录地址是
url(r'^login/$', 'django.contrib.auth.views.login',
{'template_name': 'login.html',
'extra_context': {'next': '/tasks/home/',
'title': 'Taskman | Log In'},
它确实成功登录,但是当我再次输入“/user/login”作为 URL 时,它会在成功登录后再次显示登录页面。
那么Django不处理这种情况吗?
如login
views 所示
def login(request, template_name='registration/login.html',
redirect_field_name=REDIRECT_FIELD_NAME,
authentication_form=AuthenticationForm,
current_app=None, extra_context=None):
"""
Displays the login form and handles the login action.
"""
redirect_to = request.REQUEST.get(redirect_field_name, '')
if request.method == "POST":
form = authentication_form(request, data=request.POST)
if form.is_valid():
# Ensure the user-originating redirection url is safe.
if not is_safe_url(url=redirect_to, host=request.get_host()):
redirect_to = resolve_url(settings.LOGIN_REDIRECT_URL)
# Okay, security check complete. Log the user in.
auth_login(request, form.get_user())
return HttpResponseRedirect(redirect_to)
else:
form = authentication_form(request)
current_site = get_current_site(request)
context = {
'form': form,
redirect_field_name: redirect_to,
'site': current_site,
'site_name': current_site.name,
}
if extra_context is not None:
context.update(extra_context)
return TemplateResponse(request, template_name, context,
current_app=current_app)
那么我是否必须覆盖AuthenticationForm
?
最佳答案
这是我在 Django 中经常看到的行为 - 即使您已登录,并且您尝试导航到登录页面,它也会显示登录页面。这在某些情况下是有用的行为,例如,如果一个人有多个可以登录的用户帐户,这意味着他们可以登录到不同的用户帐户而无需先注销。
如果您希望覆盖此行为,您可以通过将登录 URL 指向 RedirectView
来实现:
- 如果用户已经登录,则将他们重定向到特定页面(理想情况下,如果 URL 中提供了下一页参数,则将他们定向到该页面)。
- 如果用户没有登录,将他们重定向到实际的登录提示 View 。
希望这对您有所帮助。
关于python - Django 在已经登录时显示 Auth 登录页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23752021/