Django Authentication Tutorial Step By Step

As the title says- “Django Authentication system”, this is a complete tutorial on how the authentication system works in Django. The authentication system consists of Authentication and Authorization both. Authentication is a verification technique to verify who you are whereas Authorization clearly means whether they are allowed to perform a certain operation or not.

Authentication

Moving towards Authentication, as we know authentication only means verifying a user about its identity and who is he/she, it has nothing to do with permission. It only includes some basic details as First_name, Last_name, email, password.

Create a user

Let’s start with the authentication system first –

Starting with some basic steps-

  1. Start your project, my project name is project itself.
  2. Start your app, my app name is app only.
  3. Create a directory named, templates.
  4. Create a superuser in it.
  5. Include your app_name inside INSTALLED_APPS in the settings.py file under your project.

Once you have followed the above steps, now you need to include the path of templates to the base directory in the settings.py.

You can do this using- "DIRS": [os.path.join(BASE_DIR, "templates")],

Your template section will look like this-

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, "templates")],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

 

As you have created a superuser, this superuser has all the control and permissions. Let’s try to create a user, a user is a regular user who actually doesn’t have all the permissions but is associated with the company.

Try this in your shell as-

Start by importing the necessary package using from django.contrib.auth.models import User

Create a user- User.objects.create_user('username', 'email@codespeedy.com', 'password')

You can add the last name as –user.last_name="lastname"

Save the user using user.save()

You can skip adding the last name too. There are many methods to create a user, this is one of the simplest one. This user will be a regular user and will help us to differentiate with the two other categories of user that are staff, superuser.

 

Create a group

We have successfully created our user following the above steps now we need to create a group. A group has the advantage of grouping users together for the same kind of permissions. For example, an accountant in a school or college is supposed to have a database of fee dues of all students. We might need to permit a few people to have similar permissions, for this reason, we will create a group of all the accountants.

Whenever you visit Django Administration, you might have noticed two sections in authentication and authorization namely, groups and users. Talking about a group, it is a group of users that is used to add or remove permission in a group instead of one by one.

When you run your server, and then you navigate to the Django Administration, there you will be able to see Groups, click on Add Group.

 Django Authentication Tutorial - add group

You will be able to see a page like this, you can add permission too, as for now, we don’t need any, so we will continue to save.

Add a user using Django Administration

We can add a user by navigating back to the admin site and adding a user there.

add user in Django

This is the page to enter user details. When you enter details it will create a new user and redirect you to a page where it will ask you to change/add the details you have just entered.

user data in Django

Make sure to tick the active column. Select the group just created, I have created it with the name CSE. So, I would select CSE and then click on the right arrow to push it into the chosen group.

We created this in order to have one group and user which will be implemented in authentication and authorization.

Authorization

Authorization means whether a user is allowed to perform a certain operation or not. Take an example of a site that only allows seeing content when you create an account and show a login page until you are not logged in. We will do a similar task now.

As we have successfully created user, our task is to check whether the user is authorized or not, and what permissions does a user has.

Moving forward, we will create a function that will display details of a user.

  1. Create a view named user to fetch the following details.
  2. Define a URL to naviagte.

Define a function named user as-

def user(request):
    text = f"""
        User attributes:

        username:  {request.user.username}
        anonymous: {request.user.is_anonymous}
        staff:     {request.user.is_staff}
        superuser: {request.user.is_superuser}
        active:    {request.user.is_active}
        
    """

    return HttpResponse(text, content_type="text")

You can try logging in as different users to see these details.

We need to make changes in our urls.py also such as-

Add this code in your urlpatterns under urls.py-path("user_data/",views.user),

Run your server and navigate into user_data to check the details of a user or you can click onĀ http://127.0.0.1:8000/user_data/

You will be able to see a page like this if you are logged into Django Administration-

user attributes in Django

Username tells who you are, anonymous is true when you are logged in and false when not, staff and superuser are the permissions.

What if a user is not authenticated?

Sometimes situations arise when you need to redirect a user to a certain place if it is logged in or go back to the login page if not. We will achieve this task by a decorator known as @login_required. As for now, we will check whether a user is logged in or not, also if the user is active or not, you can also follow the above steps but this method will be a little more useful as we can redirect to the login page too.

Open your view.py file and create a decorator as-

@login_required
def login(request):
    return HttpResponse("You are an authenticated user!", content_type="text/plain")

Also, Add URL in urlpattern-

path("login/", views.login),

authenticated in Django

If in case you are not logged in it will redirect you to the login page which we will create later in this tutorial.

We already have users, one is a superuser which was created at the very beginning, next we have created a user using shell which was named as codespeedy, the next we need is a user with staff status as True to notice the differences between the three types of users.

Navigate back to the Django Administration and add a user with username and password, the password must contain letters and numbers, you can try similar to code1234speedy which is a valid password.

We were getting an error in the above code when we were not logged in, that error was because we haven’t created any login page, we need to create a login page in order to redirect a user.

Open project/urls.py and add the URL path("accounts/", include("django.contrib.auth.urls")),

in the urlpatterns.

The next step is to create a login template under templates but first, create a base.html in the templates folder created in the beginning-

<html>
<body>

{% block content %}
{% endblock content %}

</body>
</html>

Next, create an HTML file named login under registration in templates-

Code for login.html-

{% extends 'base.html' %}

{% block content %}
<h1>Login</h1>

<form method="post">
    {% csrf_token %}
    {{ form.as_p }}
    <input type="submit" value="Login">
</form>


{% endblock %}

Now, the above error is rectified as we have a login template.

authentication login form in Django

This is the output screen.

Allow permission to only staff members in Django

Sometimes we need criteria to show, edit, view or perform a certain operation. For example, a student must have paid fees in order to appear in an exam is a condition. Once a student pays a fee he/she is eligible for the exam. Above we have limited our view to only those who are authenticated users and active ones. What if we have a group of users and staff and certain permissions are only allowed to staff members. You can again take the case a staff member is allowed to retrieve all student data but not a user.

We will now use a test case decorator to check a condition and allow us to see our view.

A very simple approach towards restricting a view who are not marked as staff-

Open your urls.py and add path("staff_member/", views.staff_member),

Next, you need to use a decorator @user_passes_test which is a condition or a test case, which a user must pass in order to perform a certain operation, here we have a HttpResponse which will be available only when a user is logged in and is a staff member. What if a user is a regular user, not a staff member, he will be redirected back to the login page and asked to log in. Sounds interesting right, let’s go-

Import user_passes_test as from django.contrib.auth.decorators import user_passes_test

@user_passes_test(lambda user: user.is_staff)
def staff_member(request):
    return HttpResponse("You are logged in as a staff", content_type="text/plain")

You can log in as different users with different permission for a better understanding.

Conclusion- This tutorial has taught us types of users, how to create one, create a group, authentication, and authorization of users by allowing only certain users who have the permission.

Thank you! I hope this tutorial was helpful to understand authentication and authorization in a better way. Feel free to comment and share your reviews in the comment section.

Leave a Reply

Your email address will not be published.