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.
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 ...
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.
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.
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..
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With