简体   繁体   中英

Django redirect_authenticated_user: True not working

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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM