DEV Community

Cover image for Django Authentication System - Tutorial for Beginners
Sm0ke
Sm0ke

Posted on • Originally published at docs.appseed.us

Django Authentication System - Tutorial for Beginners

Hello Coders,

This tutorial aims to help beginners accommodate with Django Framework, especially with the authentication system provided "out-of-the-box" by this amazing framework. For newcomers, Django is an open-source web framework designed and actively supported by experienced developers with help from many open-source enthusiasts.

Thanks for reading! - Content provided by App Generator.


Topics covered in this tutorial

  • User - the core entity used to manage auth information
  • How to create a new user using the Django CLI
  • How to create a superuser
  • Create a user using UI (forms, controller, view)

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:

Django Authentication System - User model fields.

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:

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

Create a virtual environment - Linux-based systems

$ virtualenv env
$ source env/bin/activate 
Enter fullscreen mode Exit fullscreen mode

For Windows system, the syntax is different:

$ virtualenv env
$ .\env\Scripts\activate 
Enter fullscreen mode Exit fullscreen mode

Install Django

$ pip install django
Enter fullscreen mode Exit fullscreen mode

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.

$ # 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. 
Enter fullscreen mode Exit fullscreen mode

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>]>
Enter fullscreen mode Exit fullscreen mode

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')
Enter fullscreen mode Exit fullscreen mode

We can see the new users can be created with ease using the create-user helper provided by User model - Let's check again all registered users in the terminal:

>>> >>> User.objects.all()         
<QuerySet [<User: admin>, <User: test>]>
Enter fullscreen mode Exit fullscreen mode

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"
            }
        ))
Enter fullscreen mode Exit fullscreen mode

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 })
Enter fullscreen mode Exit fullscreen mode

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>
Enter fullscreen mode Exit fullscreen mode

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 })
Enter fullscreen mode Exit fullscreen mode

Thanks for reading! Feel free to AMA in the comments section. For more resources, please access:


  • Read more about Django (official docs)
  • Start fast a new project using development-ready Django Starters

Top comments (9)

Collapse
 
crearesite profile image
WebsiteMarket

The user creation using that form is great.
Thank you!

Collapse
 
sm0ke profile image
Sm0ke

Indeed. A super easy way to register a new user in Django.

Collapse
 
uithemes profile image
ui-themes

Thank you for writing!
Can I reset a password using the terminal?

Collapse
 
sm0ke profile image
Sm0ke

For sure - Here is the code to reset a password for an existing user:

>>> from django.contrib.auth.models import User 
>>> user = User.objects.get(email='test@whatever.com') 
>>> user.set_password('new_raw_password') 
>>> user.save() 
Enter fullscreen mode Exit fullscreen mode

P.S. the password should be in plain text (Django handles the encryption).

Collapse
 
uithemes profile image
ui-themes

So easy, Ty!

Thread Thread
 
sm0ke profile image
Sm0ke

🚀🚀

Collapse
 
uithemes profile image
ui-themes

Thanks!

Collapse
 
ldrscke profile image
Christian Ledermann

Why do none of the 'intrductory' posts about the user model mention how to create a custom user model? I found that this is needed for a lot of use cases

Collapse
 
sm0ke profile image
Sm0ke • Edited

Hello @ldrscke . Indeed this is hot subject.
In case you have the time, take a look at this article:
How to Extend Django User Model

Happy Coding!