In this tutorial, we’ll discuss ‘how to allow users to log in to a website with their own accounts and how to allow them to create accounts. The mechanisms work behind the scene is called authentication.

Authentication verifies a user if he is who he pretends to be, and authorization determines what an authenticated user can do.

Django by default has a user authentication system. It handles user accounts, groups, permissions and cookie-based user sessions. We will discuss the following topics here:

  • Default User Model
  • Creating User
  • Creating Super User
  • Authenticating User
  • Authentication Views
    • Log In
    • Log Out
    • Sign Up / Registration

Default User Model

There is a User model in django authentication system which is the core of authentication system. Using ‘User‘ model we can create ‘superuser‘(admin), ‘staff‘(other staff) or user(end-user).

The primary attributes of the default user are:

  • username (required)
  • password (required)
  • email (optional)
  • first_name(optional)
  • last_name(optional)

You will have to configure your project first. Otherwise, the code will not work. Follow the steps to configure your project…

1. Create Virtual Environment

2. Activate Virtual Environment

3. Create Project

4.Run Migration Commands

If all these are done, then you are ready to go. Now, you may get confused that where is the user model or which app contains the user model. After creating your project go to your ‘settings.py’ file and look inside ‘INSTALLED_APPS‘ list. here you will find the auth app.

INSTALLED_APPS =[
'django.contrib.auth', #Core authentication framework and its default models.
'django.contrib.contenttypes', #Django content type system (allows permissions to be associated with models).
]
MIDDLEWARE =[
'django.contrib.sessions.middleware.SessionMiddleware', #Manages sessions across requests
'django.contrib.auth.middleware.AuthenticationMiddleware', #Associates users with requests using sessions.
]

Creating Super User

Now, we are ready to create users. Let’s create a super user first. Super user is actually admin, who has all the permissions.We can use ‘python manage.py createsuperuser’ command to create super users.

(env) PS E:\my_project> python manage.py createsuperuser
Username (leave blank to use 'user'): admin_user
Email address: admin@gmail.com
Password:
Password (again):
The password is too similar to the email address.
This password is too short. It must contain at least 8 characters.
This password is too common.
Bypass password validation and create user anyway? [y/N]: y
Superuser created successfully.

It seems, we didn’t give any password. No, we did. Django is not showing it for security purpose. Our password was ‘admin’ which is less than 8 characters & similar too email. That’s why django is showing some warnings but we bypassed the password validation as it’s our demo project. Now, we can login as an ‘admin’ with these credentials.

Creating Normal User

Normal users are users whose ‘is_admin’ attribute is False. They are ‘End Users’. Now, we will create the normal user.

>>> from django.contrib.auth.models import User

>>>new_user = User.objects.create_user('new_user', 'new_user@gmail.com', 'my_password1234')
>>>new_user
<User: new_user>

>>> a = User.objects.all()
>>> a
<QuerySet [<User: admin>, <User: admin_user>, <User: new_user>]>

>>>new_user.last_name = 'second'
>>>new_user.save()
>>>updated_info = User.objects.get(email='new_user@gmail.com')
>>>updated_info.last_name
'second'

Authenticating Users

To authenticate a user’s username and password, we use  authenticate(**credentials) method. It takes credentials in the form of keyword arguments, for the default configuration this is username and  password, and it returns a User object if the password is valid for the given username. If the password is invalid,   authenticate() returns None.

>>> from django.contrib.auth import authenticate
>>> from django.contrib.auth.models import User

>>> new_user_2 = User.objects.create_user('new_user_2','new_user2@gmail.com','password1234')
>>> new_user_2
<User: new_user_2>

>>> user = authenticate(username='new_user_2',password='password1234')
>>> print(user)
new_user_2

>>> if user is not None:
...     print('User logged In')
... else:
...     print('User Not Avaiable')
...
User logged In

>>> user.is_active
True

Till now we were working in our python shell. What if we want to implement these in our website? Like, Sign Up, Login, Logout functionalities. Django auth module comes with all these functionalities. Here is the views that we can use when we need…

Authentication Views

We get this from ‘django.contrib.auth.views’

We will need to do a little work to implement Log In & Log out functionalities. First, we will import them in urls.py and create urls.

urls.py

from django.contrib.auth.views import LoginView, LogoutView

urlpatterns = [
    path('login/', LoginView.as_view(), name='login'),
    path('logout/', LogoutView.as_view(), name='logout'),
    ]

LoginView

Now, if we run our server and go to ‘login’ it will show a ‘TemplateDoesNotExist’ error. Because LoginView requires a form. That means will have to render a ‘Template’. The template name will have to be ‘login.html’ & it must be inside a folder named ‘registration’. Because inside Django’s LoginView the ‘template_name’ attribute is set like below:

class LoginView(SuccessURLAllowedHostsMixin, FormView):

"""
Display the login form and handle the login action.
"""

    form_class = AuthenticationForm

    authentication_form = None

    next_page = None

    redirect_field_name = REDIRECT_FIELD_NAME

    template_name = 'registration/login.html'

So, let’s create a folder named ‘registration’ and a template ‘login.html’ inside it.

Template:


<!DOCTYPE html>  
<html lang="en">  
<head>  
    <meta charset="UTF-8">  
<title>Login Form</title>  
</head>  
<body> 
    <h2>LOGIN FORM</h2>
  <form method="POST" class="post-form">  
        {{ form.as_p }}  
        {% csrf_token %}  
    <button type="submit" class="save btn btn-default">Log In</button>  
</form>  
</body>  
</html>  

Everything is set. We will login as an admin and check if we can go to ‘admin panel’

django default-admin panel

See, it’s working fine.

LogoutView

We are in admin panel now. With pressing the logout button placed in right side. Go to this url 127.0.0.1:80000/logout/ You should see the default logout page like below.

Sign Up/ Registration

We have seen how to use LoginView & LogoutView. But, the most important part of an website is to allow users to get themselves registered. Django doesn’t have any default ‘SignupView’ but it has a built – in “UserCreationForm’ that creates a user, with no privileges, from the given username and password.

from django.contrib.auth.forms import UserCreationForm
from django.urls import reverse_lazy
class SignUpView(CreateView):
    form_class = UserCreationForm
    template_name = 'registration/sign_up.html'
    success_url = reverse_lazy('login') 

We used that form as the value of ‘form_class’ attribute of our SignUpView. Now, we will create a ‘sign_up.html’ template and add this view in urls.

Template:

<!DOCTYPE html>  
<html lang="en">  
<head>  
    <meta charset="UTF-8">  
<title>Sign Up Form</title>  
</head>  
<body> 
    <h2>SIGN UP FORM</h2>
  <form method="POST" class="post-form">  
        {{ form.as_p }}  
        {% csrf_token %}  
    <button type="submit" class="save btn btn-default">Sign Up</button>  
</form>  
</body>  
</html>  

Output

After pressing ‘Sign Up’ button it will redirect us to ‘login’ page. Now, we will log in as admin and check if the user is saved or not.

Admin panel

Everything is working fine.Here, we have taken inputs of required fields only. We can take ‘first_name’, ‘last_name’ also by implanting child class of ‘UserCreationForm’ or We can create our own Custom Authentication Module.

+ posts

Author | Python-Django Developer

+ posts

Full-stack Developer (Python | Django | React | React-Native | Angular | Vue)