You want to authenticate users but you’re unsure how. The documentation isn’t the most helpful thing in the world. You think, “wow… this documentation assumes I know all this other stuff…”
What are the things you need to authenticate users? There are 3 things you need and I’m going to show you what each looks like.
First: You need some routes
You need authentication routes. I think it makes the most sense to create a separate app for this purpose. (Separate all your login logic from all your other logic)
Let’s look at some login routes:
Second: You’ll need some templates
Templates are important. Templates are the HTML representation of your application. For example, at the bare minimum, you’ll need a way to let your users login. How do you do it? It doesn’t have to be pretty because this is JUST HTML.
Third: You’ll need some views
The views you’ll need for login will be:
- The login form view (shows the login form)
- The POST view that will authenticate a user that is active / exists
- A view that will log the user out
Let’s start with the login form view (loginapp/auth):
This view simply renders our
login.html template that we created above. It’s also possible to make only 2 routes (1 that will detect a POST request and 1 that will detect a GET request) however, I (personally) really like have separate views for each request method.
Here is an example of a view that will detect a username and password and use those credentials to authenticate a user and login the user thus creating a session specifically for that user.
This method will get the
password from the POST request data. Then, we will use the
password to try to authenticate a user that exists in our database.
If a user exists, we will try to login our user and redirect to our
polls application. If the user does not exist we will redirect back to the login form.
How do you logout an authenticated user?
This method will take the request object and user it to logout the logged in user. Once the user logs out, the application will redirect the user to our
This is the 3 things that you need to authenticate users in your Django application. (If you want to use Session Authentication with Django REST Framework) this is how you would accomplish this.
I hope that helps you when need to authenticate users in your future web application.