Part -9

Authenticate Users In Django

Django have built-in views for logging in and out users,so in blog_project/urls.py let’s import them as

from django.contrib.auth import views as auth_views

Since we are importing multiple views here so I make use of as keyword ,and we have imported them then we’ll create paths for them

...
path('login/',auth_views.LoginView.as_view(template_name='users/login.html'),name='login'),
path('logout/',auth_views.LogoutView.as_view(),name='logout'),

And now I’ll make the login template under template/users folder..

{%extends ‘blogapp/base.html’%}
...
<form method='POST'>
{%csrf_token%}
{{form|crispy}}
<button type='submit'>Submit</button>
Need An Account? <a href='{%url 'register'%}'>Sign Up</a></form>
...

Notice that I added {%url ‘register’%} for redirecting users to Sign up form,you can do this in your Sign Up form as well for redirecting users to login form if they already have an account.

And now when you go to 127.0.0.1.800/login and enter wrong credentials,you’ll see validation error

And when I enter wrong credentials,

We can see that django is redirecting users to accounts/profile when they’ve successful login,so let’s change the default to where the django should redirect users when they’ve successfully logged in.In settings.py add this line add at the very bottom of the file(you can change it to ‘login’ as well)

LOGIN_REDIRECT_URL='blog-home'

Remember that this was the name we gave to our index page path.

now let’s logout using /logout and you’ll see

We logged out of our django admin panel,and if we click back on login again with the link provides it directs us to the django administration login,we would’nt want such redirection for the users other than staffs to see these pages.So all we need to do is to create a template for logout page and map it to logout view just as we did for login view.

path('logout/',auth_views.LogoutView.as_view(template_name="users/logout.html"),name='logout'),{% extends "blogapp/base.html" %}
{% block body %}
<h2>You have been logged out</h2>
<a href="{% url 'login' %}">Log In Again</a>
{% endblock body %}

And now logging out doesn’t really logout user from the admin page.

Next Up..

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store