Codementor Events

How and why I built a user authentication module in Django

Published May 28, 2018Last updated Nov 24, 2018
How and why I built  a user authentication module in Django

About me

I'm anjansrivathsav, pursuing my B tech third year at the Indian Institute of Information Technology Vadodara. My areas of interest are full-stack development, deep learning, and Android application development.

The problem I wanted to solve

I have built a user sign-in and sign-up module, and the user profile using the Django framework. The motivation behind building this module is that this is an implementation everyone requires when building any blog or website. There are a few basic mistakes that people make in building this, so I wanted to solve this problem.

What is it that I have built in Django?

The user authentication module basically works by allowing a user to sign up and build his profile, which consists of a profile picture, as well as other personal and technical information. One can sign-up, add their information, and change their information later by signing into the module.

Tech stack

The technologies used in building this module are Django for the back-end and Bootstrap for the front-end. I have chosen Django as it is a high level web framework. It delivers high quality code writing, and developer will find it very easy and comfortable to build. Bootstrap is used to create responsiveness, and other Technologies like HTML and CSS are also used.

The process for building a user authentication module in Django

I will now demonstrate the process of building in different steps:

  1. Initialize a project with the command:
    django-admin startproject <projectname>

  2. Go inside the directory and create an app inside the project with the command:
    python manage.py startapp <appname>

  3. Now type the command:

     -> python manage.py migrate
     -> python manage.py runserver
    
  4. In the terminal you will be able to see the server running on the specific port number;
    go to the port number and you'll see the Django server running.

  5. No,w go to the settings file, add your 'app name' in the installed apps list, create the template, static, and the media directories as:

    TEMPLATE_DIR = os.path.join(BASE_DIR,'templates')

    You can also create the media and static directories with different variablesm and create the folders in the directories.

  6. Basically, the HTML files go into the templates directory, the static files into the static folder, and the media files into the media folder.

  7. Change into the directory of your app, and inside the models folder import the following:

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

    Now, you can create a model and specify its parameters:

      class UserInfo(models.Model):
      user = models.OneToOneField(User)
    

    The user one to one field is matched, and now you can add any number of fields here like the url field, image field, etc.

  8. Creating the views inside the views.py file of your app. The import statements are:

    from django.contrib.auth import authenticate, login, logout
    from django.http import HttpResponseRedirect, HttpResponse
    from django.core.urlresolvers import reverse
    from django.contrib.auth.decorators import login_required
    

These are imported for authentication purposes.

  1. The views can be as follows:
    ```
    def _logout(request):
    logout(request)

      def registration(request):
            if request.method == 'POST':
                 get the values from the 
                 form and validate the particular values and save them
    
  2. For the login part:

              def login(request):
                    request.method == 'POST':
                     get the values of username and password 
                  validate with the inbuilt authenticate function  as
             user = authenticate(username,password)
    then login(user ) is done the user is logged in and the responses could be sent
    
  3. In the urls.py section, you will write the urls for the created views and of the type:

              urlpatterns=[
                                    url(r'^register/$',views.register,name='register'),
                                    url(r'^user_login/$',views.user_login,name='user_login'),
                                   ]
    
  4. Now inside the templates create the HTML pages.

  5. Inside the admin.py file, add the model name that we have created. The format will be: admin.site.register(Mymodelname)

  6. You can also create the forms of each and every user input in the forms.py file.

    • Create a file forms.py.
    • Import the statement
      from django import forms.
    • A basic example of the Form is:
    class UserProfileInfoForm(forms.ModelForm):
    class Meta():
     model = Modelname
     fields = ('field-1','field-2')
    

    This is an example of model form. This can be imported in views and sent as the response to the front-end to be loaded. This form enables the values of the fields you have mentioned in the model. You can even add extra fields in the field section.

  7. This is the outline and the things that need to be done to build user login and sign-up fields:

     python manage.py makemigrations
     python manage.py migrate
     python manage.py runserver
    
  8. Go to the browser and see your module running in localhost.

Challenges I faced

The main challenge is analyzing what is happening in the structure. Once you understand the structuring and functionalities of the Django layout, it becomes quite interesting and easy to proceed furthur.

Tips and advice

Django provides various services and the documentation is made very neatly. Reading the documentation helps you understand things and helps you make cool projects.

Final thoughts and next steps

I want to write a series of blog posts on Django development, like building a blog,
website, video service, and some other cool projects like building a real time Django chat application.

Thanks!

Discover and read more posts from anjansrivathsav
get started
post commentsBe the first to share your opinion
mtr khan
4 years ago

Nice, Can you please make an article related to custom user management:-

  1. create page for user listings with user id, user name, firstname, lastname, email, mobile number, status(active,Inactive), user type(admin, employee), job type(job1, job2, job3), add pagination, filters and search functionality
  2. Create form for Add user :- username, firstname, lastname, email, mobile number, status, type and job role
  3. Edit user
  4. Delete user
    Send random password to email of user after create any user.
    Each user can able to login on same panel with there provided credential.
    Use JWT token instead of session

with templates and users app in navbar

Show more replies