🚀
AppSeed Docs
  • AppSeed
  • Support
  • App Generator
  • Boilerplate Code
    • API Servers
      • API Unified Definition
      • API Server Django
      • API Server Flask
      • API Server Node JS
    • Boilerplate Django Dashboards
    • Boilerplate Django Apps
    • Boilerplate Flask Dashboards
    • Boilerplate Flask Apps
    • Boilerplate Jinja
    • Django Templates
      • Django Template Volt
      • Django Argon Dashboard
      • Django Material Dashboard
  • Developer Tools
    • Django API Generator
    • Django Dynamic API
    • Django Dynamic DataTables
    • Flask Dynamic API
    • Flask Dynamic DataTables
    • DB Introspection Tool
  • PRODUCTS
    • Full-stack
      • Full-Stack React Purity
      • Full-Stack React Material
      • Full-Stack React Datta Able
      • Full-Stack React Berry
    • React
      • React Node JS Berry
      • React Node JS Datta Able
      • React Node JS Datta PRO
      • React Node Material Kit PRO
      • React Firebase Datta Able
      • React Firebase Datta PRO
      • Django React Datta Able
      • Django React Datta PRO
      • Flask React Datta Able
    • Flask Apps
      • Flask Material Kit
      • Flask Material Kit PRO
      • Flask Material Kit 2 PRO
      • Flask Pixel Lite
      • Flask Pixel PRO
      • Flask Soft Design
      • Flask Soft Design PRO
    • Flask Dashboards
      • Flask Adminator
      • Flask AdminLTE
      • Flask Azia Dashboard
      • Flask Argon Dashboard
      • Flask Argon PRO
      • Flask Atlantis Dark
      • Flask Atlantis Dark PRO
      • Flask Black Dashboard
      • Flask Black PRO
      • Flask CoreUI
      • Flask Datta Able
      • Flask Datta Able PRO
      • Flask Datta Able ENH
      • Flask Gradient Able
      • Flask Light Bootstrap
      • Flask Light Blue
      • Flask Material Dashboard
      • Flask Material PRO
      • Flask MaterialPro Lite
      • Flask MaterialPRO
      • Flask Material Admin
      • Flask Star Admin
      • Flask Soft Dashboard
      • Flask Soft Dashboard Pro
      • Flask Shards Dashboard
      • Flask SB Admin
      • Flask Sleek Admin
      • Flask Volt
      • Flask Volt PRO
      • Flask Tabler
    • Django Apps
      • Django Pixel Lite
      • Django Pixel PRO
      • Django Material Kit
      • Django Material Kit PRO
      • Django Material Kit 2 PRO
      • Django Soft Design
      • Django Soft Design PRO
    • Django Dashboards
      • Django Adminator
      • Django AdminLTE
      • Django Azia Dashboard
      • Django Argon Dashboard
      • Django Argon PRO
      • Django Atlantis Dark
      • Django Atlantis Dark PRO
      • Django Black Dashboard
      • Django Black PRO
      • Django CoreUI
      • Django Datta Able
      • Django Datta Able PRO
      • Django Datta Able ENH
      • Django Gradient Able
      • Django Light Bootstrap
      • Django Light Blue
      • Django Material Dashboard
      • Django Material PRO
      • Django MaterialPro Lite
      • Django MaterialPro
      • Django Star Admin
      • Django Soft Dashboard
      • Django Soft Dashboard PRO
      • Django Soft Dashboard ENH
      • Django Shards Dashboard
      • Django SB Admin
      • Django Volt
      • Django Volt PRO
      • Django Tabler
    • Eleventy 11ty
      • Soft UI Design
    • Jinja Templates
      • Jinja Argon Dashboard
      • Jinja AdminLTE
      • Jinja Atlantis Lite
      • Jinja Black Dashboard
      • Jinja Datta Able PRO
      • Jinja Dashkit v3
      • Jinja Light Bootstrap
      • Jinja Material Dashboard
      • Jinja Now UI Dashboard
      • Jinja Paper Dashboard
      • Jinja Pixel Lite
      • Jinja Pixel PRO
      • Jinja SB Admin
      • Jinja Volt Bootstrap 5
      • Jinja Volt PRO
  • Features
    • Flask
      • Extended User Model
  • Free Samples
    • Django Samples
      • Django Create Model
      • Django User Profile
      • Django Sales Charts
      • Django Routing Sample
      • Django API Server
  • Technologies
    • Django
      • Getting Started
      • Django v4 Release
    • FastAPI
      • Getting Started
    • Flask
      • Getting Started
      • Flask v2.0 Release
    • MySql
      • Install MySql on Windows
      • Install MySql on Ubuntu
    • Material UI
      • Getting Started
    • Next JS
      • Getting Started
      • Sample Next.js Project
      • Deploy a Next.js application on Netlify
      • Best Practices for NextJS projects
    • Python
      • Getting Started
    • Supabase
      • Getting Started
  • Deployment
    • Google Cloud Platform
      • Deploy Django on GCP
    • App Platform by DO
      • App Platform - Deploy Django
    • AWS - Amazon Services
      • Deploy Django on AWS
    • Render Deployment Platform
      • Deploy Flask to Render
      • Deploy Django to Render
      • Deploy React to Render
      • Deploy Django & React to Render
  • Content
    • What IS
      • What IS Apache
      • What IS Bulma
      • What IS Boilerplate Code
      • What IS CentOS
      • What IS Django
      • What IS Eleventy
      • What IS Flask
      • What IS Gunicorn
      • What IS Heroku
      • What IS JAMStack
      • What IS Jinja
      • What IS Nginx
      • What IS Panini
      • What IS Pipenv
      • What IS Python
      • What IS React
      • What IS Static Site
      • What IS Svelte
      • What IS Ubuntu
      • What IS uWsgi
      • What IS WSGI
      • Two-Tier Architecture
      • Single-Tier Architecture
      • N-Tier Architecture
    • Getting Started
      • Getting Started with Django
      • Django Templates
      • Getting Started with Flask
      • Getting Started with Next JS
    • How To
      • OAUth - Get Github Secrets
      • OAUth - Get Twitter Secrets
      • Crawl Website in Python
      • Setup CentOS for coding
      • Setup Ubuntu for coding
      • Setup Windows for coding
      • Install Pyhton
      • Install Pyhton 3.8 on Ubuntu
      • Install WSL
      • Install Docker on Windows
      • Getting Started with Python
      • Django Customize Admin UI
      • Django Chart Example
      • Django - Add Debug Toolbar
      • Django MySql Database
      • Django Dockerizing App
      • Django Reset Password
      • Django Extend User Model
      • Django Integrate DRF Library
      • Django Data Tables
      • Django Simple Charts
      • Django Social Login
      • Django Stripe Payments
      • Django HEROKU Deployment
      • Django AWS Deployment
      • Django Google Cloud Deploy
      • Django Azure Deployment
      • Install Flask
      • Code a simple app In Flask
      • Structure a Flask project
      • Flask Dockerizing App
      • Flask Reset Password
      • Flask User Profile
      • Flask Integrate Flask-RestX
      • Flask Data Tables
      • Flask Simple Charts
      • Flask Social Login
      • Flask Stripe Payments
      • Flask Deploy on Apache
      • Flask Deploy on HEROKU
      • Flask AWS Deployment
      • Flask Google Cloud Deploy
      • Flask Azure Deployment
      • How to Implement JWT Authentication in React
    • Tutorials
      • Django - How to Install
      • Django For Beginners
      • Django Request Object
      • Django Forms
      • Django Auth System
      • Flask - Code a simple App
      • Minimal Programming Kit
      • Parse HTML Components
    • Programming Languages
      • Php
      • Python
    • Frameworks
      • Django
      • Flask
    • Design Systems
      • Argon Design System
      • Soft UI Design System
    • Partners
      • BootstrapDash Agency
      • Creative-Tim Agency
      • CodedThemes Agency
      • CoreUI Agency
      • Themesberg Agency
      • WrapPixel Agency
    • Bootstrap Templates
      • Adminator
      • AdminKit
      • AdminLTE
      • Azia Dashboard PRO
      • Atlantis Lite Template
      • Atlantis PRO Template
      • Argon Dashboard Template
      • Argon Dashboard PRO
      • Black Dashboard Template
      • Black Dashboard PRO
      • CoreUI Template
      • Datta Able Template
      • Datta Able PRO Template
      • Light Bootstrap Template
      • Light Bootstrap PRO
      • Material Dashboard Template
      • Material Dashboard PRO
      • Material UI Kit
      • MaterialPro Lite
      • MaterialPro Wpx
      • Now UI Dashboard
      • Now UI Dashboard PRO
      • Paper Dashboard
      • Paper Dashboard PRO
      • Pixel Lite Template
      • Pixel PRO
      • Star Admin Template
      • Soft UI Dashboard
      • Soft UI Dashboard PRO
      • Shards Dashboard
      • Volt Dashboard Template
      • Volt Dashboard Pro Template
      • Tabler Template
    • Bulma CSS Templates
      • Dashkit PRO
      • Dashkit PRO v3
    • React Templates
      • Berry React Dashboard
      • CoreUI React
    • Vue Templates
      • Vuetify Material Dashboard
    • How to Fix
      • Cannot import name 'TextField' from 'wtforms'
      • ImportError: cannot import name 'safe_str_cmp' from 'werkzeug.security'
Powered by GitBook
On this page
  • User Model
  • Create Users - Django CLI
  • Create Users via UI
  • Authenticated User
  • Logout Users
  • Resources

Was this helpful?

  1. Content
  2. Tutorials

Django Auth System

Learn how to manage users in Django with ease - tutorial for beginners.

PreviousDjango FormsNextFlask - Code a simple App

Last updated 3 years ago

Was this helpful?

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:

  • - simple, tested steps to install Django

  • - a comprehensive tutorial that covers the basics

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

test@appseed.us

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 provided by the AppSeed Team to explain many Django concepts:

$ git clone https://github.com/app-generator/django-learn-by-coding.git
$ cd django-learn-by-coding

Create a virtual environment - Linux-based systems

$ virtualenv env
$ source env/bin/activate 

For Windows system, the syntax is different:

$ virtualenv env
$ .\env\Scripts\activate 

Install Django

$ pip install django

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

$ # We are in the ROOT of the project
$ python manage.py createsuperuser
sername (leave blank to use 'test'): admin
Email address: test@appseed.us
Password: ********
Password (again): ********
Superuser created successfully. 

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:

>>> from django.contrib.auth.models import User 
>>> User.objects.all()                         
<QuerySet [<User: admin>]>

We can see the new admin saved a few seconds ago.

>>> admin = User.objects.all()[0] # Slice - get the first object
>>> admin.id
1
>>> admin.username
'admin'
>>> admin.password
'pbkdf2_sha256$260000$g3i1kS5WQLQbeND5AS4CRD$Ekn9VOH9o0T6DsF5Vll5mZupslzwDjI348Q8eDwNeIw=' 

Using the CLI we can explore all properties and of course update fields.

Create a new (common) user

>>> from django.contrib.auth.models import User
>>> user = User.objects.create_user('test', 'test@appseed.us', 'Super_S3cret111')

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:

>>> >>> User.objects.all()         
<QuerySet [<User: admin>, <User: test>]>

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

class SignUpForm(UserCreationForm):
    username = forms.CharField(
        widget=forms.TextInput(
            attrs={
                "placeholder" : "Username"
            }
        ))
    email = forms.EmailField(
        widget=forms.EmailInput(
            attrs={
                "placeholder" : "Email"
            }
        ))
    password1 = forms.CharField(
        widget=forms.PasswordInput(
            attrs={
                "placeholder" : "Password"
            }
        ))
    password2 = forms.CharField(
        widget=forms.PasswordInput(
            attrs={
                "placeholder" : "Password check"
            }
        ))

Create the controller

def register_user(request):

    # A user-friendly message 
    msg = None

    # User submits the credentials 
    if request.method == "POST":
        
        # Initialize the from POST data
        form = SignUpForm(request.POST)
        
        # Check all constraints (one line)
        if form.is_valid():
        
            # Create the user
            form.save()
            
            msg     = 'User created successfully.'
            
        else:
            msg = 'Form is not valid'    
    
    # Show the SignUp Page 
    else:
        form = SignUpForm()

    return render(request, "accounts/register.html", {"form": form, "msg" : msg })

The page that shows the form and invite the user to register

<form role="form" method="post" action="">

    {% csrf_token %}                    

    <div>
        {{ form.username }}
    </div>
    <span class="text-error">{{ form.username.errors }}</span>

    <div>
        {{ form.email }}
    </div>
    <span class="text-error">{{ form.email.errors }}</span>

    <div>
        {{ form.password1 }}
    </div>
    <span class="text-error">{{ form.password1.errors }}</span>

    <div>
        {{ form.password2 }}
    </div>
    <span class="text-error">{{ form.password2.errors }}</span>
    
    <button type="submit" name="register">Register</button>

</form>

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:

def register_user(request):

    # A user-friendly message 
    msg = None

    # User submits the credentials 
    if request.method == "POST":
        
        # Initialize the from POST data
        form = SignUpForm(request.POST)
        
        # Check all constraints (one line)
        if form.is_valid():
        
            username     = form.cleaned_data.get("username")  # <-- UPDATED      
            email        = form.cleaned_data.get("email")     # <-- UPDATED 
            raw_password = form.cleaned_data.get("password1") # <-- UPDATED
            
            # Create user: UPDATED
            new_user = User.objects.create_user(username, email, raw_password)
            
            msg     = 'User created successfully.'
            
        else:
            msg = 'Form is not valid'    
    
    # Show the SignUp Page 
    else:
        form = SignUpForm()

    return render(request, "accounts/register.html", {"form": form, "msg" : msg })

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

def testme(path):

    # Redirect guests users to login page
    if request.user.is_authenticated:
        return HttpResponse("User authenticated")
    else:
        return HttpResponse("Access forbidden - please authenticate")

Check user is authenticated in views

    <!-- The Usage of <current_user> object -->
    {% if request.user.is_authenticated %}

        <!-- Html chunk rendered for authenticated users-->

    {% else %}

        <!-- Html chunk rendered for guests users-->

    {% endif %}

Logout Users

The logout helper is provided by Django.contrib.auth middleware package:

# Logout action sample
from Django.contrib.auth import logout 
 
def my_logout_view(request): 
    logout(request)

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.

Resources

Thanks for reading! For more topics, feel free to Appseed.

Read more about (official docs)

Start fast a new project using development-ready

How to install Django
Django for beginners
open-source sample
contact
Django
Django Starters