Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 379
Anuj TBE Avatar asked Sep 10 '17 19:09

Anuj TBE


People also ask

How to authenticate user login in Django?

from django.contrib.auth import authenticate, login def my_view(request): username = request.POST['username'] password = request.POST['password'] user = authenticate(request, username=username, password=password) if user is not None: login(request, user) # Redirect to a success page. ... else: # Return an 'invalid ...

How to logout a user in Django?

Here to handle the logout functionality, we need to import the "logout" built-in Django function and "login_required" decorator. We need this decorator to make sure that users who are trying to log out are authenticated or, in simple terms - logged in.

How do I add login requirements in Django?

Create an app folder in the django project folder. Add template folder in the django folder and provide its path in django_folder > settings.py . Create file named as urls.py in the app folder and provide its path in django_project > urls.py. Add login decorator to the function in app_folder > views.py.

How to create new user in Django?

The correct way to create a user in Django is to use the create_user function. This will handle the hashing of the password, etc..


1 Answers

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

like image 199
Josh K Avatar answered Sep 24 '22 05:09

Josh K