Django 7 - Users login, logout and register
Tags: django, python, docker, postgres
Published: 2024-04-29 04:03:49

> _NOTE: This article was initially posted on my Substack, at https://andresalvareziglesias.substack.com/_

Hi everyone!

Django makes the user and session management easy. With every app, a user table is automatically generated, with a full management UI in the admin site, as we saw in previous parts of this series.

Now, we will integrate this users/session management in our game UI.

## Articles in this series

- Chapter 1: [Let the journey start](https://andresalvareziglesias.substack.com/p/let-the-journey-start-with-python-docker-and-ai?utm_source=post-toc)
- Chapter 2: [Create a containerized Django app with Gunicorn and Docker](https://andresalvareziglesias.substack.com/p/create-a-containerized-django-app?utm_source=post-toc)
- Chapter 3: [Serve Django static files with NGINX](https://andresalvareziglesias.substack.com/p/serve-django-static-files-with-nginx?utm_source=post-toc)
- Chapter 4: [Adding a database to our stack](https://andresalvareziglesias.substack.com/p/adding-a-database-to-our-stack?utm_source=post-toc)
- Chapter 5: [Applications and sites](https://andresalvareziglesias.substack.com/p/django-5-applications-and-sites)
- Chapter 6: [Using the Django ORM](https://andresalvareziglesias.substack.com/p/django-6-using-the-django-orm)
- Chapter 7: [Users login, logout and register](https://andresalvareziglesias.substack.com/p/django-7-users-login-logout-and-register)

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8fqg9ho49o3qakv1qlmv.png)

## Login in or registering

We can make a simple login form like this:

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ikli59229qfauhnl0ans.png)

As the text says, if the user does not exist yet, it will be automatically generated. While we can create a simple login form that automatically generates users on login attempts, this approach poses significant security risks. It leaves your application vulnerable to brute-force attacks, where attackers can repeatedly try different usernames and passwords to gain access. For each attempt, a new user would be created, further compromising your system.  This approach should **never** be used in a production environment.

To develop this functionality, we need a view like this:

```
from django.shortcuts import redirect
from django.contrib.auth import authenticate, login
from django.contrib.auth.models import User

def loginView(request):
   username = request.POST.get("username", ""),    
   password = request.POST.get("password", ""))

   # Try to log in first
   user = authenticate(username=username, password=password)
   if user is not None and user.is_active:
       login(request, user)
       return redirect("index")

   # Validate user and password
   if User.objects.filter(username=username).exists():
       return redirect("index")

   if (len(password) < 8 orpassword.find(username) != -1):
       return redirect("index")

   # The user does not exists, create now
   user = User.objects.create_user(username=username, password=password)
   login(request, user)
   return redirect("index")
```

The relevant parts of the following view are the user login:

```
user = authenticate(username=username, password=password)
if user is not None and user.is_active:
    login(request, user)
```

And the user creation (and later login):

```
user = User.objects.create_user(username=username, password=password)
login(request, user)
```

As you can see, Django simplifies user account creation, authentication, and session handling for us. 

## Login out

We need to allow our users to close their sessions. Considering a simple "logout" link like this:

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xozs8zte7jf90pu00i94.png)

We can develop a logout view like this:

```
from django.shortcuts import redirect
from django.contrib.auth import logout

def logoutView(request):
   logout(request)
   return redirect("index")
```

As simple as that. Django handles user session termination for us. Cool!

## What have we learned so far?

We have walked a long trip in our journey to learn Django. Now, we are able to:

- Create a Django app
- Create any number of independent or interconnected subapps inside our app
- Develop an HTML/Javascript web UI with a separated Python backend
- Integrate our app with a database
- Manage the user session

And we have learned a few things about architecture:

- Generate interconnected services with Docker
- Code a docker-compose file to create all environment in an easy way
- Basic usage of gunicorn to serve our Django app
- Basic usage of NGINX to serve the static parts of the site (and to route gunicorn calls)
- Basic usage of PostgreSQL with Timescale exension

We now have the basic resources to develop any full-stack application, from user interface to backend and data layer.

Now, it's time to develop our Tic-Tac-Toe game. Let's play!

## About the list

Among the Python and Docker posts, I will also write about other related topics (always tech and programming topics, I promise... with the fingers crossed), like:

- Software architecture
- Programming environments
- Linux operating system
- Etc.

If you found some interesting technology, programming language or whatever, please, let me know! I'm always open to learning something new!

## About the author

I'm Andrés, a full-stack software developer based in Palma, on a personal journey to improve my coding skills. I'm also a self-published fantasy writer with four published novels to my name. Feel free to ask me anything!