Django Logging Users In and Out

Django provides built-in URL patterns and view functions which makes adding login and logout system to your site a breeze. But before we add them to our project, we will create login and logout system on our own by using some utility functions provided by the Django authentication framework.

The authenticate() and login() functions

Django authentication framework (django.contrib.auth) provides authenticate() and login() functions whose job is to authenticate and login users respectively.

The authenticate() function accepts two keyword arguments, username and password and returns an object of type User, if username and password are valid. Otherwise, it returns None.

The authenticate() function only verifies whether the credentials provided are valid or not. It doesn’t login the user.

To login user we use login() function. It takes two arguments, request object (HttpRequest) and a User object. To login user it saves the user’s ID in the session, using Django session framework.

Once a user is logged in, he should be able to logout and this is the responsibility of logout() function.

The logout() function

To logout users we use logout() function. It accepts a request (HttpRequest) object and returns None. Calling logout() function completely deletes the session data associated with the logged in user.

It is important to note that calling logout() function doesn’t throw any errors if the user is not logged in.

The logout() function also removes the cookie from the browser.

Another Login System

Now we have enough knowledge to roll out our own login system.

In the blog’s app add login(), logout() and admin_page() views as follows:


Then create three templates login.html, logout.html and admin_page.html as follows:




Finally, add the following URL patterns in the blog’s file:


Start the development server and visit You should get a page like this:

Enter correct username and password and you will be greeted with a page like this:

Nothing extraordinary here, we are just using some of the attributes we have learned in earlier lesson to get some information about the current logged in user.

To logout, click the logout link at the bottom of the page.

Using built-in login() and logout() views

Django provides two views django.contrib.auth.login() and django.contrib.auth.logout() to login and logout users respectively.

To use these views, import django.contrib.auth package and then add the following two URL patterns in the cadmin’s app file:


By default, Django uses /accounts/login/ and /accounts/logout/ URL for login and logout respectively.

Save the file and visit You will get a TemplateDoesNotExist exception as follows:

The problem is that by default, django.contrib.auth.login() view looks for registration/login.html template in the templates directory of the auth app (django.contrib.auth). Because there is no such file in the templates directory of the auth app, Django raises a TemplateDoesNotExist exception.

We can pass a different template to the django.contrib.auth.login() view using the template_name keyword argument as follows:

Similarly, by default the django.contrib.auth.logout() view uses registration/logged_out.html template from the admin app (django.contrib.admin). This is the same template which you would see if you logout from the Django Admin site.

Visit and see it yourself.

Just as with django.contrib.auth.login() view, we can use a different template by passing template_name keyword argument to django.contrib.auth.logout() view as follows:

We will create custom templates for login and logout page. So modify login and logout URLs to include template name in cadmin’s file as follows:


Before we create login and logout templates, let’s create another URL pattern which points to the root URL (i.e of the cadmin app. Add a URL pattern named home to the urlpatterns list in file as follows:


Then, in the cadmin file add the home() view just below post_update() view as follows:


The only thing that remains now is the templates for the login, logout and admin page. Let’s start by creating login template first.

Create a new file named login.html inside cadmin app’s templates directory (i.e cadmin/templates/cadmin/) and add the following code to it:


The value of the form template variable will be provided by django.contrib.auth.login() view using context.

Create another template named logout.html with the following code.


Finally, create admin_page.html and add the following code to it.


Our login view is almost ready. Visit and try logging in using wrong username and password. You will be greeted with errors like this:

Try logging in one more time using the correct username and password. If user logged in successfully then the django.contrib.auth.login() view will redirect the user to /accounts/profile/ URL, this is Django’s another default setting kicking in.

We don’t have any URL pattern in cadmin’s for /accounts/profile/ that’s why an HTTP 404 error is displayed.

We can override this setting by adding a hidden field (in login.html) named next with the URL to redirect after login.

This will redirect the user to, after successful login.

Instead of hardcoding the URL. We could also pass the value of the next field using query string like this:

Open login.html and add the hidden field named next as follows:


This is how the above code works:

If we don’t provide any value to next form field as query string then the default value i.e /cadmin/ will be used. Otherwise, the user will be redirected to the URL given by the next as a query string.

Visit, enter correct username/password and hit enter. This time you will be redirected to, which looks like this:

To logout click “Logout” link at the bottom of the page or visit and you will see a page like this:

Our login and logout system is working as expected, but from the usability point of view, there is still one problem.

Visit once again and login using the correct username and password. As expected, you will be redirected to At this point, if we visit again, Django will redisplay the login the form. Redisplaying login form to a logged in user is absolutely pointless.

We can change this behavior by creating a custom login view function. Open cadmin app’s and append the login() view as follows:


Nothing new here except the additional **kwargs argument. The kwargs enables us to pass the all the extra keyword arguments passed to this view function to the built-in django.contrib.auth.login() view function.

Here is how it works:

The login() view first checks whether the user is authenticated or not. If the user is authenticated then it will redirect him to the admin page. Otherwise, it will display the login form by calling built-in django.contrib.auth.login() view.

Next, we have to update our login URL pattern to use our login() view instead of one provided by Django Authentication framework. Update login URL pattern in as follows:


Now if you visit after logging in, you will be redirected to

Limiting Access

The whole point of implementing login system to our site is to prevent unauthorized access to administrative pages.

A simple way to restrict access to a page is to first check whether the user is authenticated or not using is_authenticated() method then redirect the user accordingly. For example:

We have already employed this technique in the home() and login() view functions.


In Django, the preferred way to limit access to pages is to use login_required decorator. To use login_required decorator you must import it from django.contrib.auth.decorators.

Let’s update home() view to use login_required decorator as follows:


Here is how the login_required decorator work:

If the user is not logged then it will redirect the user to /accounts/login/ (Django’s default login URL), passing the current absolute URL as a value to the next query parameter. For example, open your browser and visit (without logging in). The login_required will redirect you to URL.

On the other hand, if the user is logged in then the login_required would do nothing. In the next section, we are going to change Django’s default login URL i.e /accounts/login/.

Updating default Login URL

In the earlier sections, we have encountered many places where Django uses /accounts/login/ as default URL for login. To change default login URL we use LOGIN_URL setting in file. LOGIN_URL accepts URL or name of the URL pattern. Open file and add the following variable at the end of the file.

Here we are assigning the value of the name attribute of login URL pattern from cadmin’s In other words, the above code changes the default login URL from /accounts/login/ to /cadmin/accounts/login/. As a result, if you try to visit a view which has login_required decorator applied to it, you will be redirected to /cadmin/accounts/login/ URL instead of /accounts/login/.

In our case, we want users to let users to login and logout using /cadmin/login/ and /cadmin/logout/ URLs respectively. To do so, open cadmin’s file and make the following changes:


As we are using named URL pattern in LOGIN_URL setting we don’t need to update anything else. Now our updated login and logout URLs are /cadmin/login/ and /cadmin/logout/ respectively. To verify the changes visit and you will be redirected to

Enter correct username and password and you will get a page like this:

Note: To checkout this version of the repository type git checkout 30a.

5 thoughts on “Django Logging Users In and Out

  1. if request.user.is_authenticated():
    return render(‘cadmin’)

    This return the following error:
    UnboundLocalError: local variable ‘user’ referenced before assignment

  2. When someone writes an post he/she keeps the plan of a
    user in his/her brain that how a user can understand it. So that’s why this article is
    perfect. Thanks!

Leave a Comment

%d bloggers like this: