Django comes with a lot of built-in resources for the most common use cases of a Web application. The registration app is a very good example and a good thing about it is that the features can be used out-of-the-box.
With the Django registration app you can take advantages of the following features:
- Sign up
- Password reset
In this tutorial we will focus in the Login and Logout features. For sign up and password reset, check the tutorials below:
Before we start, make sure you have
django.contrib.auth in your
INSTALLED_APPS and the authentication middleware
properly configured in the
Both come already configured when you start a new Django project using the command
startproject. So if you did not
remove the initial configurations you should be all set up.
In case you are starting a new project just to follow this tutorial, create a user using the command line just so we can test the login and logout pages.
In the end of this article I will provide the source code of the example with the minimal configuration.
Configure the URL routes
First import the
django.contrib.auth.views module and add a URL route for the login and logout views:
Create a login template
By default, the
django.contrib.auth.views.login view will try to render the
registration/login.html template. So
the basic configuration would be creating a folder named
registration and place a
login.html template inside.
Following a minimal login template:
This simple example already validates username and password and authenticate correctly the user.
Customizing the login view
There are a few parameters you can pass to the
login view to make it fit your project. For example, if you want to
store your login template somewhere else than
registration/login.html you can pass the template name as a parameter:
You can also pass a custom authentication form using the parameter
authentication_form, incase you have implemented
a custom user model.
Now, a very important configuration is done in the
settings.py file, which is the URL Django will redirect the user
after a successful authentication.
settings.py file add:
The value can be a hardcoded URL or a URL name. The default value for
It is also important to note that Django will try to redirect the user to the
next GET param.
Setting up logout view
After acessing the
django.contrib.auth.views.logout view, Django will render the
template. In a similar way as we did in the
login view, you can pass a different template like so:
Usually I prefer to use the
next_page parameter and redirect either to the homepage of my project or to the login
page when it makes sense.
Running the example locally
The code used in this short tutorial is available at GitHub.
Clone the repository:
Create a user:
Run the server:
127.0.0.1:8000/login in your web browser.
Read more about the Django registration views in the official documentation clicking here.