Django redirect_authenticated_user: True not working

半世苍凉 提交于 2020-02-21 13:29:09

问题


I'm writing an application in Django 1.11.

myapp/urls.py pattern looks like

from django.conf.urls import url, include
from django.contrib import admin
from django.contrib.auth.views import LoginView

urlpatterns = [
    url(r'^login/$', LoginView.as_view(), {'redirect_authenticated_user': True}),
    url('^', include('django.contrib.auth.urls')),
    url('^', include('pages.urls')),
    url(r'^pages/', include('pages.urls')),
    url(r'^search/', include('search.urls')),
    url(r'^admin/', admin.site.urls),
]

I want logged in user to be redirected when trying to access /login page. For that I have set redirect_authenticated_user to True as per given in documentation here

But, when I access /login after successful login, it does not redirect.


回答1:


Pass redirect_authenticated_user to as_view():

urlpatterns = [
    url(r'^login/$', LoginView.as_view(redirect_authenticated_user=True)),

Any arguments passed to as_view() will override attributes set on the class. In this example, we set template_name on the TemplateView. A similar overriding pattern can be used for the url attribute on RedirectView.

From Simple usage in your URLconf




回答2:


For anyone looking into this using Django 2 you would actually use kwargs similar to OP.

from django.contrib.auth import views as auth_views

urlpatterns = [
    path('login/', auth_views.login, {'redirect_authenticated_user': True}, name='login'),
]

https://docs.djangoproject.com/en/2.0/topics/http/urls/#views-extra-options



来源:https://stackoverflow.com/questions/46144824/django-redirect-authenticated-user-true-not-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!