Django Auth System
Learn how to manage users in Django with ease - tutorial for beginners.
Being a "batteries-included" framework, Django comes with a powerful authentication/authorization system that we can use and extend in our projects with ease. For those that start from nothing, feel free to access the resources mentioned below and come back here once the content is understood:
Topics covered in this tutorial
    User the table where the information is saved
    How to create a new user using the Django CLI
    How to create a superuser
    How to update the password - Django CLI
    Create a user using forms

User Model

As mentioned in the official Django documentation, the User model represents the core entity used to save and manage authentication. The fields managed by the User model can be found below:
Field
Sample Value
Information
username
test
Mandatory Field
password
Super_S3cret
optional for inactive users
email
optional
fist_name
John
optional
last_name
Doe
optional
Probably the most simple way to create a new user in Django is to use the CLI (Django shell). In case you don't have already a Django project, feel free to clone an open-source sample provided by the AppSeed Team to explain many Django concepts:
1
$ git clone https://github.com/app-generator/django-learn-by-coding.git
2
$ cd django-learn-by-coding
Copied!
Create a virtual environment - Linux-based systems
1
$ virtualenv env
2
$ source env/bin/activate
Copied!
For Windows system, the syntax is different:
1
$ virtualenv env
2
$ .\env\Scripts\activate
Copied!
Install Django
1
$ pip install django
Copied!
​

Create Users - Django CLI

The user creation process using the terminal is usually related to the superuser that allows us to access the admin section. For newcomers, the admin section manages the registered users, groups defined in our project.
Create the superuser in Django
1
$ # We are in the ROOT of the project
2
$ python manage.py createsuperuser
3
sername (leave blank to use 'test'): admin
4
Email address: [email protected]
5
Password: ********
6
Password (again): ********
7
Superuser created successfully.
Copied!
Once the superuser admin is created we can access the admin section and interact with all models registered by our project. Let's explore the users using the Django CLI:
1
>>> from django.contrib.auth.models import User
2
>>> User.objects.all()
3
<QuerySet [<User: admin>]>
Copied!
We can see the new admin saved a few seconds ago.
1
>>> admin = User.objects.all()[0] # Slice - get the first object
2
>>> admin.id
3
1
4
>>> admin.username
5
'admin'
6
>>> admin.password
7
'pbkdf2_sha256$260000$g3i1kS5WQLQbeND5AS4CRD$Ekn9VOH9o0T6DsF5Vll5mZupslzwDjI348Q8eDwNeIw='
Copied!
Using the CLI we can explore all properties and of course update fields.
Create a new (common) user
1
>>> from django.contrib.auth.models import User
2
>>> user = User.objects.create_user('test', '[email protected]', 'Super_S3cret111')
Copied!
As we can see, new users can be created with ease using the create-user helper provided by User model - Let's check again all registered users:
1
>>> >>> User.objects.all()
2
<QuerySet [<User: admin>, <User: test>]>
Copied!

Create Users via UI

Using the console to create and manage users might be fun but might be also useful in our projects to allow users to register themselves using a public web page. To do this, we need a simple page where the form is exposed and a backend to handle the information sent to the user.
Create the SignUp Form
1
class SignUpForm(UserCreationForm):
2
username = forms.CharField(
3
widget=forms.TextInput(
4
attrs={
5
"placeholder" : "Username"
6
}
7
))
8
email = forms.EmailField(
9
widget=forms.EmailInput(
10
attrs={
11
"placeholder" : "Email"
12
}
13
))
14
password1 = forms.CharField(
15
widget=forms.PasswordInput(
16
attrs={
17
"placeholder" : "Password"
18
}
19
))
20
password2 = forms.CharField(
21
widget=forms.PasswordInput(
22
attrs={
23
"placeholder" : "Password check"
24
}
25
))
Copied!
Create the controller
1
def register_user(request):
2
​
3
# A user-friendly message
4
msg = None
5
​
6
# User submits the credentials
7
if request.method == "POST":
8
9
# Initialize the from POST data
10
form = SignUpForm(request.POST)
11
12
# Check all constraints (one line)
13
if form.is_valid():
14
15
# Create the user
16
form.save()
17
18
msg = 'User created successfully.'
19
20
else:
21
msg = 'Form is not valid'
22
23
# Show the SignUp Page
24
else:
25
form = SignUpForm()
26
​
27
return render(request, "accounts/register.html", {"form": form, "msg" : msg })
Copied!
The page that shows the form and invite the user to register
1
<form role="form" method="post" action="">
2
​
3
{% csrf_token %}
4
​
5
<div>
6
{{ form.username }}
7
</div>
8
<span class="text-error">{{ form.username.errors }}</span>
9
​
10
<div>
11
{{ form.email }}
12
</div>
13
<span class="text-error">{{ form.email.errors }}</span>
14
​
15
<div>
16
{{ form.password1 }}
17
</div>
18
<span class="text-error">{{ form.password1.errors }}</span>
19
​
20
<div>
21
{{ form.password2 }}
22
</div>
23
<span class="text-error">{{ form.password2.errors }}</span>
24
25
<button type="submit" name="register">Register</button>
26
​
27
</form>
Copied!
The user registration mechanism
    The User sees the registration page
    The User inputs all fields
    The form is submitted and the controller receives all information (username, password)
    If the form is valid, the form is saved and the user is created
    A confirmation message is returned to the user
The above sample uses a form to create the user but we can update the code to use the create-user method as well:
1
def register_user(request):
2
​
3
# A user-friendly message
4
msg = None
5
​
6
# User submits the credentials
7
if request.method == "POST":
8
9
# Initialize the from POST data
10
form = SignUpForm(request.POST)
11
12
# Check all constraints (one line)
13
if form.is_valid():
14
15
username = form.cleaned_data.get("username") # <-- UPDATED
16
email = form.cleaned_data.get("email") # <-- UPDATED
17
raw_password = form.cleaned_data.get("password1") # <-- UPDATED
18
19
# Create user: UPDATED
20
new_user = User.objects.create_user(username, email, raw_password)
21
22
msg = 'User created successfully.'
23
24
else:
25
msg = 'Form is not valid'
26
27
# Show the SignUp Page
28
else:
29
form = SignUpForm()
30
​
31
return render(request, "accounts/register.html", {"form": form, "msg" : msg })
Copied!
​

Authenticated User

Django hooks the authenticated in the request object and we can check if a request is done by an authenticated user or not by calling a helper. The same check is available in views.
Check user is authenticated in controller - is_authenticated (boolean) property
1
def testme(path):
2
​
3
# Redirect guests users to login page
4
if request.user.is_authenticated:
5
return HttpResponse("User authenticated")
6
else:
7
return HttpResponse("Access forbidden - please authenticate")
Copied!
Check user is authenticated in views
1
<!-- The Usage of <current_user> object -->
2
{% if request.user.is_authenticated %}
3
​
4
<!-- Html chunk rendered for authenticated users-->
5
​
6
{% else %}
7
​
8
<!-- Html chunk rendered for guests users-->
9
​
10
{% endif %}
Copied!
​

Logout Users

The logout helper is provided by Django.contrib.auth middleware package:
1
# Logout action sample
2
from Django.contrib.auth import logout
3
4
def my_logout_view(request):
5
logout(request)
Copied!
If the user is authenticated all session information will be deleted. If the user is not authenticated, the logout helper will run without returning errors or exceptions.
​
Thanks for reading! For more topics, feel free to contact Appseed.
​

Resources

Last modified 3mo ago