Anuj TBE
Anuj TBE

Reputation: 9790

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.

Upvotes: 7

Views: 5043

Answers (2)

Scott Sword
Scott Sword

Reputation: 4708

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

Upvotes: 3

Josh K
Josh K

Reputation: 28883

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

Upvotes: 16

Related Questions