Custom User Authentication Using Django

Aakash Verma
7 min readJun 28, 2020

--

Hi there ! I’m up again with another topic which is very important while building any kind of user oriented site or web app i.e. User Registration/Login System .

In this article I will walk you through the basic steps required to have a login system using Django Web Framework , user will be able to Sign Up/Sign In to the site and we will learn about restricting pages for non-authenticated users to access a particular page in the site . So let’s begin…

Pre-requisites: — Well there is not much of knowledge needed but I assume you are well acquainted with basic python understanding and know how web works …!!!

step 1: — Download and install Python as per your system Os . (Link)

mkdir login_system
cd login_system

make a directory named login_system in your desktop or wherever you want to store your project into .

step 2: — Set up a virtual environment around login_system . It is recommended that you use virtualenv to create isolated Python environments, so that you can use different package versions for different projects, which is far more practical than installing Python packages system-wide

pip install virtualenv

After you install virtualenv, create an isolated environment with the following command:

virtualenv my_env

This will create a my_env/ directory, including your Python environment. Any Python libraries you install while your virtual environment is active will go into the my_env/lib/python3.6/site-packages directory.

Run the following command to activate your virtual environment:

source my_env/bin/activate          ## for mac usersmy_env\Scripts\activate\            ## for windows user"""You can deactivate your environment at any time with the deactivate command.
"""

step 3: — Installing Django

Run the following command at the shell prompt to install Django with pip:

pip install Django==3.0.7

Django will be installed in the Python site-packages/ directory of your virtual environment. Now, check whether Django has been successfully installed. Run python on a terminal, import Django, and check its version, as follows:

>>> import django 
>>> django.get_version()
‘3.0.7’

If you get the preceding output, Django has been successfully installed on your machine.

Now we will create a Django project inside our login_system directory

what is Django project ?

Django project is a place where all the database configuration, server settings, app Url settings files are located. It can have multiple apps inside it .

django-admin.py startproject mysite

Above command will create a folder named mysite inside our login_system directory . If you look inside this folder it contains some files , those are,

manage.py: This is a command-line utility used to interact with your project. It is a thin wrapper around the django-admin.py tool. You don’t need to edit this file.

mysite/: This is your project directory, which consists of the following files:

__init__.py: An empty file that tells Python to treat the mysite directory as a Python module.

settings.py: This indicates settings and configuration for your project and contains initial default settings.

urls.py: This is the place where your URL patterns live. Each URL defined here is mapped to a view.

wsgi.py: This is the configuration to run your project as a Web Server Gateway Interface (WSGI) application.

Now its time to create a app in which we will be putting our logic ,

cd mysite
python manage.py startapp app

Above cmd will create app folder inside our root mysite directory,

now tree structure must look something like this,

#Directory Tree Structure 
login_system/
myenv/
mysite/
app/
__init__.py
admin.py
apps.py
models.py
views.py
tests.py
mysite/
__init__.py
asgi.py
settings.py
urls.py
wsgi.py
manage.py

Edit settings.py of your project folder ,

#settings.py
import os
...
...
...
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'app', #new
]

This will let Django project know that an app named app exists .

now when inside mysite root directory run this command

python manage.py runserver

This command starts the development server so that we can test our application in development phase . Now go to http:/.localhost:8000 or http:/.127.0.0.1:8000

If you see the above page running that means our setup is Successfull …

From Here We start our actual work of user login/Registration.

The User Model :

The User object (located at django.contrib.auth.models.User) is considered to be the core of Django’s authentication system. A User object represents each of the individuals interacting with a User Authentication Django application.

The User model has five key attributes.

They are:

  • the username for the user account
  • the account’s password
  • the user’s email address
  • the user’s first name
  • the user’s surname

If you want to add Additional User Attributes , start by editing models.py file in app folder.

class UserProfile(models.Model):

user = models.OneToOneField(User, on_delete=models.CASCADE)
website = models.URLField(blank=True)
picture = models.ImageField(upload_to='profile_images/',\
blank=True
)
def __str__(self):
return self.user.username

After creating model for our User profile we will run migrations .The migrations can be said as Django’s way of propagating changes you make to your models into your database schema .

run following command,

python manage.py makemigrations app
python manage.py migrate

you will notice in your console something like this

Operations to perform:
Apply all migrations: admin, auth, contenttypes, sessions, app
Running migrations:
Applying contenttypes.0001_initial... OK
Applying auth.0001_initial... OK
Applying admin.0001_initial... OK
Applying admin.0002_logentry_remove_auto_add... OK
Applying admin.0003_logentry_add_action_flag_choices... OK
Applying contenttypes.0002_remove_content_type_name... OK
Applying auth.0002_alter_permission_name_max_length... OK
Applying auth.0003_alter_user_email_max_length... OK
Applying auth.0004_alter_user_username_opts... OK
Applying auth.0005_alter_user_last_login_null... OK
Applying auth.0006_require_contenttypes_0002... OK
Applying auth.0007_update_proxy_permissions... OK
Applying sessions.0001_initial... OK

You will notice something like above in your console . That is django applying migrations to the database.

Creating a User Registration View : —

We will focus on 2 main points here -

1 . create a UserForm and UserProfileForm .

2 . add a view to handle the creation of a new user .

Creating forms

Now inside app folder create a new file forms.py , and paste(or write ) the following code ,

#app/forms.pyfrom django import forms 
from django.contrib.auth.models import User
from app.models import Userprofile
class UserForm(forms.ModelForm):
password = forms.CharField(widget=forms.PasswordInput())

class Meta:
model = User
fields = ('username', 'email', 'password')
class UserProfileForm(forms.ModelForm):

class Meta:
model = UserProfile
fields = ('website', 'picture')

Notice that in both classes we added a Nested Meta class , actually anything within a nested Meta class describes additional properties about the particular class to which it belongs. Each Meta class must supply a model field and you also need to specify the fields or the fields to exclude . Here ,we only want to show the fields username, email and password associated with the User model, and the website and picture fields associated with the UserProfile model. . We also need to update the password attribute to specify that the CharField instance should hide a user’s input from preying eyes through use of the PasswordInput() widget.

The register() View : —

Here we will handle both the rendering of the form and the processing of form input data,

Login View() :

Home View:-

In above

Templates:-

We need to generate a base template so that our other template files can extend the base template and we need not to write the same code in every file . Create a templates folder in your root project directory and in settings.py file edit the following :

so we have set the path of our templates folder to which django look for when finding the template files for particular view function .

Now inside templates folder that we created , create a base.html file and add the following code in it .

Note :- I have used Bootstrap4 to make our site more interactive

Registration Template :

Now we need to make a template that will be used by the new register() view. Create a new template file named registeration.html

In above registration template code we extended base.html so that we have same orientation of website as we have in home page and then we rendered user_form and profile_form sent by our registration view .

login template :-

Now create a login.html in our templates folder and add the following code in that file,

In above login.html file ,we extended the base template as usual and then rendered the form having two inputs , one for username and other for password .

Home page template :-

In above home.html file , we first extended base template so that orientation persists then we have a welcome message for the user who sign up to our website . and we also display the username using request object which is available to us by Django.

URL’s :-

Now that we have done with view and templates we will set up URL for our site . Go to url.py folder of our mysite project . and add these code.

in above mysite/urls.py file we included our login app urls.py file so that Django know where to serve the request for our views .

Now create a new urls.py file in our app folder and add the following code in it.

This urls.py file we are creating will handle all the urls for the view functions for our app .

Now that verything is set lets run the server ,

Go to terminal and in your project directory , make sure your virtual environment is activated , run the following command,

python manage.py runserver

This runs the built-it development server that comes with Django.

Now in your web browser go to http://127.0.0.l:8000/app/register , you will notice that our registration page gets loaded there. Try registering a new user there and then login using same credentials . Once done you will be redirected to a our home page with the welcome message . If you face any errors kindly revisit each code and cross check if you made any errors or not .And if it further exists then feel free to write your errors in comments I will try to solve them each…

--

--

Aakash Verma

Computer Science Undergrad ,Tech Enthusiast , Loves writing about Technology