User System — Registration, Login, Logout
In this chapter you will learn to use Django's built-in authentication system to implement user registration, login, and logout.
Django's built-in auth system
Django comes with a complete user authentication module:
- built-in
UserModel (username, password, email, etc.) - Built-in login/logout views (no need to write logic yourself)
- Built-in permission and group management
- Form validation and security protection (CSRF, XSS)
This module is django.contrib.auth, and is registered by default in INSTALLED_APPS when the project is created.
Registration page
Django has built-in login/logout views, but no built-in registration view, so we need to write it ourselves.
Step 1: Create a registration form
Example
File path: blog/forms.py (new file)
from
django
import
forms
from
django.
contrib
.
auth
.
forms
import
UserCreationForm
from
django.
contrib
.
auth
.
models
import
User
class
RegisterForm
(
UserCreationForm
)
:
"""Custom registration form: inherit from UserCreationForm, add an email field"""
=
forms.
EmailField
(
label
=
'Email'
,
required
=
True
,
help_text
=
'Please enter a valid email address.'
)
class
Meta:
model
=
User
fields
=
[
'username'
,
'email'
,
'password1'
,
'password2'
]
labels
=
{
'username'
:
'Username'
,
}
Step 2: Write the registration view
Example
File path: blog/views.py, newly added
from
django.
shortcuts
import
render
,
redirect
from
django.
contrib
.
auth
import
login
from
django.
contrib
import
messages
from
.
forms
import
RegisterForm
def
register
(
request
)
:
"""User registration view"""
If the user is already logged in, redirect to the home page directly
if
request.
user
.
is_authenticated
:
return
redirect
(
'index'
)
if
request.
method
==
'POST'
:
The user submitted the registration form
form
=
RegisterForm
(
request.
POST
)
if
form.
is_valid
(
)
:
user
=
form.
save
(
)
Save the user to the database
login
(
request
,
user
)
Automatically log in after registration
messages.
success
(
request
,
f
'Registration successful, welcome you, {user.username}!'
)
return
redirect
(
'index'
)
else
:
GET request: display a blank registration form
form
=
RegisterForm
(
)
return
render
(
request
,
'blog/register.html'
,
{
'form'
: form
,
'title'
:
'Registration - RUNOOB Blog'
}
)
Django's
messagesframework is used to pass one-time messages between requests (such as "registration successful"). Render the messages area in the template, and the user can see the operation feedback. It works together with session, and the message disappears automatically after being displayed once.
Login and logout
Django has built-in login and logout views; just import them in the routes.
Example
File path: blog/urls.py
from
django.
urls
import
path
from
django.
contrib
.
auth
import
views
as
auth_views
from
.
import
views
urlpatterns
=
[
path
(
''
,
views.
index
,
name
=
'index'
)
,
path
(
'post/int:pk/'
,
views.
post_detail
,
name
=
'post_detail'
)
,
path
(
'register/'
,
views.
register
,
name
=
'register'
)
,
Django built-in login view
template_name: specify which template to use
path
(
'login/'
,
auth_views.
LoginView
.
as_view
(
template_name
=
'blog/login.html'
,
redirect_authenticated_user
=
True
Logged-in users visiting login are redirected directly
)
,
name
=
'login'
)
,
Django built-in logout view
path
(
'logout/'
,
auth_views.
LogoutView
.
as_view
(
)
,
name
=
'logout'
)
,
]
Configure the redirect addresses for login and logout in settings.py:
Example
File path: add at the end of blog_project/settings.py
LOGIN_URL
=
'login'
Unlogged users visiting a protected page are redirected to the login page
LOGIN_REDIRECT_URL
=
'index'
After successful login, redirect to the home page
LOGOUT_REDIRECT_URL
=
'index'
After logout, redirect to the home page
Create authentication-related templates
Login template
Example
{% extends 'blog/base.html' %}
{% block title %}Login - RUNOOB Blog{% endblock %}
{% block content %}
{% endblock %}
Registration template
Example
{% extends 'blog/base.html' %}
{% block title %}Registration - RUNOOB Blog{% endblock %}
{% block content %}
{% endblock %}
{% csrf_token %}is Django's security mechanism to prevent cross-site request forgery attacks. Any POST form must include it, otherwise Django will reject the request (403 error). This tag generates a hidden input containing a random CSRF token.
Display login status in the navigation bar
Update the navigation bar of base.html to display different content according to login status.
Example
RUNOOB Blog
Django's template context processor automatically injects
{{ user }}into every template, without manually passing it in views.py. You can useuser.is_authenticatedto determine whether the user is logged in.
Login page styling
Example
/* append to the style in base.html */
.auth-form
{
max-width
:
400px
;
margin
:
40px
auto
;
padding
:
30px
;
background
:
#fff
;
border-radius
:
12px
;
box-shadow
:
0
2px
12px
rgba
(
0
,
0
,
0
,
0.08
)
;
}
.auth-form
h2
{
margin-bottom
:
24px
;
text-align
:
center
;
}
.auth-form
.form-group
{
margin-bottom
:
16px
;
}
.auth-form
label
{
display
:
block
;
margin-bottom
:
6px
;
font-weight
:
500
;
}
.auth-form
input
{
width
:
100%
;
padding
:
10px
12px
;
border
:
1px
solid
#ddd
;
border-radius
:
6px
;
font-size
:
14px
;
}
.btn-submit
{
width
:
100%
;
padding
:
12px
;
background
:
#2c3e50
;
color
:
#fff
;
border
:
none
;
border-radius
:
6px
;
font-size
:
16px
;
cursor
:
pointer
;
margin-top
:
10px
;
}
.error-msg
{
color
:
#e74c3c
;
font-size
:
14px
;
}
.form-footer
{
margin-top
:
16px
;
text-align
:
center
;
font-size
:
14px
;
}
.user-name
{
color
:
#2c3e50
;
font-weight
:
500
;
}
Chapter Summary
In this chapter you integrated Django's built-in authentication system: inherited UserCreationForm to create a registration form, used LoginView/LogoutView to implement login and logout, used csrf_token to protect POST requests, and used user.is_authenticated in templates to determine login status.
Now the blog has a complete user registration, login, and logout flow.