How to create a User Registration System in Python ?

We generally explore a lot of websites on our daily day bases it could be any type of website for example Facebook, Instagram, Google, Twitter, Reddit,  Quora, Wikipedia,  or it could be your favourite blog such as Antonio's Blog, Real Python, Free Code Camp, Cave of Programming, Bustle, GSM Arena, etc. For Some of the website we use to register ourselves and log into them by providing our username, email, phone number, and password now in some websites almost all services are available for all users such as blogs and forums but in some websites such as Facebook, Instagram, Twitter, and Google some services or all of their services are restricted to registered users. Have you ever think that what is registration system, How it does work ? Are you excited to create web applications and want to start by creating something like This ? Then you are on the right place just stick around here and you will get for what you are seeking.

What is user registration system ?

As the name suggests this is a system which register a user to a website or in a program by taking some credentials of the user such as his first name, last name, gender, age, address, etc. to clarify the identity of the user and after that user creates a unique username and password to classify him on that database of that program or site to use some restricted services for registered users the user provides his one to one credentials such as username, email, phone number and password to the authentication system of that program or website this process is known as logging in into the program or website. 

How to create a user registration system with Python and Django ?
To create user registration system we first need to create a Django project this tutorial is beginner friendly for those of you who don’t know about  Django it is a web framework which is used by enterprises or companies or individuals to create modern day web applications, web frameworks generally reduces the complexity in creating web applications and websites. So, to follow along this tutorial you first need to install Django by running the following command in your terminal or command prompt

$ pip install django      

After that create a new project  with Django and  go to the directory of that project by running the following commands ->

$ python -m django startproject registration_system
$ cd registration_system

Now in the following project that we have just created  we need to create an app for further management of forms, database models, templates (registration page, login page, and logout page), static files (css, javascript, and images)  Therefore, it becomes necessary to create an app with in our project by running the following command.

$ python manage.py startapp users  

After creating users app we need to configure it to installed apps in our settings of our project.

registration_system/registration_system/settings.py

INSTALLED_APPS = [
    .............,
    'users.apps.UsersConfig',
    .............,
    ]

Code Editor:
For creating our site we have used VS Code a code editor by Microsoft VS Code is really helpful for writing code of any language , for creating GUI Applications, for creating PhoneGapps, and Web Application using various languages and modern libraries , Such as Node.js, Angular.js, Vue.js, Django etc. code editor is something preferable while creating Application with any language like a Python Console App, or GUI App but while creating a full stack website we need a code editor as we will use different type of extensions(.html, .css, .js and .python) you can install any code editor  Such as Atom, Sublime Text, VS Code and NotePad++ or an  enrich Python IDE Such as, PyCharm, Wing IDE, PyDev, and Active State Komodo IDE which could support these different extensions(.html, .css, .js, .python).

We are not creating any miss conception here you can even use default Text Editor such as Notepad on Windows , TextEdit on Mac OS, and Code Edit on Linux in Linux name of Text Editor may be differ from distribution to distribution. Or You can use even default IDLE come pre-installed with Python but for this you need to take care of indentation , blocks , errors , exceptions all by yourself.

Now the file structure of our project will look like this you can use your text editor to view these files

      registration_system/
     ├──registration_system/
    │   ├── __init__.py       
    │   ├── settings.py
    │   ├── urls.py
    │   └── wsgi.py
    ├──users/
    │   ├── __init__.py
    │   ├── migrations/
    │       └── __init__.py
    │   ├── admin.py
    │   ├── apps.py
    │   ├── models.py
    │   ├── tests.py
    │   └── views.py
    └── manage.py

For the beginners,

  •         __init__.py: Indicate all directories as Python Packages.
  •         Apps.py: is the file which contains configuration of our app with in our project,
  •         Admin.py: this file contains the settings for our Django Administration,
  •         Models.py: it contains classes which are further converted into database tables by Django.
  •         Tests.py: It contains test classes
  •         Views.py: It contains all the pages to be displayed in our project with associative functions and classes.
To create HTML pages with in our app named Users we need to create a folder named templates and inside the folder we need to create another folder named users remember for Django conventions it is necessary to name this folder as same as the app name this directory will look like this

registration_system/users/templates/users

Now Here, In This Directory you can create HTML Pages (Templates)
We will create a signup.html file here inside that HTML file we need to create a form of four fields User Name, Email, Password, Confirm Password
For styling of our page we will put our css code on our head part by using style tag

<!DOCTYPE html>
<html>    
    <head>
        <style>
            *{
              margin0
              padding0;
             }
            body{
             backgroundurl(https://htmlcolorcodes.com/assets/images/html-color-codes-color-tutorials-hero-00e10b1f.jpg); 
             font-family: sans-serif;
             }
            
            .form-wrap
               width320px
               backgroundlinear-                              gradient(rgba(0,0,0,0.5),rgba(0,0,0,0.5)); 
               padding40px 20px
               box-sizing: border-box; 
               position: fixed; 
               left50%
               top50%
               transformtranslate(-50%-50%);
              }

            h1{
               text-align: center; 
               color#fff
               font-weight: normal; 
               margin-bottom20px;
              }
            
            input{
              width100%
              background: none; 
              border1px solid #fff
              border-radius3px
              padding6px 15px
              box-sizing: border-box; 
              margin-bottom20px
              font-size16px
              color#fff;
              }
            
             button
               background#bac675
               border0
               cursor: pointer; 
               color#3e3d3d;
             }
            button:hover
               background#a4b15c
               transition.6s;
            }

        </style>
    </head>
    <body>
        <div class="form-wrap">
            <form method="POST">
            {% csrf_token %}
              <h1>Sign Up</h1>
              <font style="color: bisque;">{{ form }}</font>
              <button type="submit">Sign Up</button>
            </form>
          </div>

    </body>
</html>


After creating HTML Page we need to register it to our views.  We do not need to create our form manually we can use Django Forms instead. to do so in our views we need to import UserCreationForm from django.contrib.auth.forms  after that we will create a variable named form and will assign UserCreationForm function as its value after that inside the render function' parameters we will create a dictionary in which we will create a key and assign our variable form that we have just created as its value.


from django.shortcuts import render
from django.contrib.auth.forms import UserCreationForm

def register(request):
    form = UserCreationForm()
    return render(request, 'users/signup.html', {'form': form})


After creating a function for our page we need to add an  url pattern for our sign up page so that our template can be displayed in our browser for that we will go to urls.py of our project and import views of our Users app as app_views don’t worry it is just an identifier for our views you can name it what so ever, you want.


from users import views as app_view

urlpatterns = [
    path('admin/', admin.site.urls),
    path('signup', app_view.signup),
]


We could not load our HTML Pages by directly putting their path to the file:/// Protocol for that we need run our server by using manage.py runserver command. After that our server will run by using hyper text transfer protocol (http) on port 8000 on local host. Now don’t worry about these technical terms you just need to run this command the server will start automatically.

$ python manage.py runserver 

After that input the following URL into your browser
http://localhost:8000/signup 
If everything goes right you will see the following result




Now you can see that it does have only three fields username, password, and password confirmation but for our site we need to add email in our form. To add email field with in our form we need to create another file in our app named forms.py

from django import forms
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm

class SignUpForm(UserCreationForm):
    email = forms.EmailField()
    
    class Meta():
        model = User
        fields = ['username','email','password1','password2']

Here in our forms.py we have added email field to Django forms by creating a class named SignUpForm with UserCreationForm as its only parameter. Inside this class we have created another native class meta to add email field with in other fields. Now our form will have Email Field added  in it.




In our form while creating our form inside our form tag we have added a attribute called method and assign POST as its value <form method="POST">
supported request method which is often used in submitting a web form most commonly this is used for storing data

In our case the Django will look for the request method and if it is POST then it will give request.POST parameter to our SignUpForm method and it will construct form instances for further validation if form has some data in it will be validated and the data will be saved else the form will not be saved.

We will create these changes to our views.py to complete our Sign Up

Now you might be wondering about what that POST mean? Actually it is a HTTP 

from django.shortcuts import render, redirect
from .forms import SignUpForm
from django.contrib import messages

def signup(request):
    if request.method == 'POST':
        form = SignUpForm(request.POST)
        if form.is_valid():
            form.save()
            username = form.cleaned_data.get('username')
            messages.success(request, f'Account for, { username } has been created you can login now! ')
            return redirect('admin')

        else:
            form = SignUpForm()
    return render(request, 'users/signup.html', {'form': form})


We Have not created any Login page till now So, to do that create a copy of sign up form change the heading to log in and change the width and add height to our log in page and save it with the name login.html in our templates directory.


<!DOCTYPE html>
<html>
    <head>
        <style>
            *{margin0padding0;}
            body{backgroundurl(https://htmlcolorcodes.com/assets/images/html-color-codes-color-tutorials-hero-00e10b1f.jpg); font-familysans-serif;}
            
            .form-wrapwidth320pxheight370pxbackgroundlinear-gradient(rgba(0,0,0,0.5),rgba(0,0,0,0.5)); padding40px 20pxbox-sizingborder-boxpositionfixedleft50%top50%transformtranslate(-50%-50%);}
            h1{text-aligncentercolor#ffffont-weightnormalmargin-bottom20px;}
            
            input{width100%backgroundnoneborder1px solid #fffborder-radius3pxpadding6px 15pxbox-sizingborder-boxmargin-bottom20pxfont-size16pxcolor#fff;}
            
            buttonbackground:  #ff2c37width100%height35pxborder-radius15pxfont-size19pxcursorpointercolor#ffffff;}
            button:hoverbackground:  #bd2d34transition.6s;}
        </style>
         <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">
    </head>
    <body>
        <div class="form-wrap">
            <form method="POST">
            {% csrf_token %}
              <h1>Log In</h1>
              <font style="color: bisque;">{{ form }}</font>
              <button type="submit">Log In</button>
            </form>
          </div>
    </body>
</html>


Now for the authentication we do not need to create something Django will handle it for us we just need to import views from django.contrib.auth as authentication in our project URLs again its just am identifier you can name it whatever you want

Django will look for the username and password to the users database if both matches to some user the user will be logged in else it will show some error.


from django.contrib.auth import views as authentication

After that create a rout for our login page here we just need to specify the location of our login template or page to the Django authentications

path('login/', authentication.LoginView.as_view(template_name = 'users/login.html'), name='login'),

To access the database of users we need to create a super user or site admin first for that use the following command

$ python manage.py createsuperuser  

This will give you a small prompt in your terminal there you have to create a username, password and have to provide an email address too. If in any case you find some error while doing that like migrations are not created or something please run the following command to correct it

 $ python manage.py migrate 

This will make sure that all the migrations with in our project such as user, auth, groups etc. are working properly

After that run your site as shown before in this tutorial and try to login with those user name and password that you have created for super user
You will find the following page not found error 





because by default Django looks for the profile rout after login but this is showing an error because we have not created one but for now you can login to our admin page by simply changing the rout to admin and you will find that you have logged in




And yes you might be facing an error while loading the site without using the signup or login or admin rout as we have not assigned an empty rout for some page in our site SO, let’s remove the login/ rout from url patterns to load login page while the user load our site if the user is registered he can login else he have to create an account to access our site.

path('',authentication.LoginView.as_view(template_name = 'users/login.html'),name='login'),

Our site do not have any home page so Let’s Create One.

<!DOCTYPE html>
<html>
    <head>
        <style>
            @import url('https://fonts.googleapis.com/css?family=Raleway&display=swap');
            @import url('https://fonts.googleapis.com/css?family=Josefin+Sans|Raleway&display=swap');
            @import url('https://fonts.googleapis.com/css?family=Domine&display=swap');
            body{
            backgroundurl(https://htmlcolorcodes.com/assets/images/html-color-codes-color-tutorials-hero-00e10b1f.jpg);   
            }
            .container {
            padding16px;
            }
            
            .wrap
            width95%
            height87%;
            backgroundlinear-gradient(rgba(0,0,0,0.5),rgba(0,0,0,0.5)); 
            padding10px 20pxbox-sizingborder-boxpositionfixedleft50%top50%
            transformtranslate(-50%-50%);
            }
            
            .blog-title {
            margin-top30px;
            margin-bottom0;
            font-size60px;
            font-weightnormal;
            }
            .blog-post {
            margin-bottom60px;
            }
            h1{
            margin-top0;
            font-family'Raleway'sans-serif;
            font-family'Josefin Sans'sans-serif;
            font-weight700;
            }
            p {
            font-family'Raleway'sans-serif;
            font-weight200;
            color#fff;
            }
            @media (min-width1200px) {
            .container {
                width970px;
            }
            }
            
        </style>
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
    </head>
    <body>
        <div class="wrap">
            <div class="container">
                <div class="row">
                <div class="col-sm-8 blog-main">
                    <div class="blog-post">
                        <font style="color: #ff2c37;"><h1 class="blog-title">Welcome to our site !</h1></font>
                        <hr>
                        <p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.</p>
                        <p>Cum sociis natoque penatibus et magnis <a href="#">dis parturient montes</a>, nascetur ridiculus mus. Aenean eu leo quam. Pellentesque ornare sem lacinia quam venenatis vestibulum. Sed posuere consectetur est at lobortis. Cras mattis consectetur purus sit amet fermentum.</p>
                        <blockquote>
                        <p>Curabitur blandit tempus porttitor. <strong>Nullam quis risus eget urna mollis</strong> ornare vel eu leo. Nullam id dolor id nibh ultricies vehicula ut id elit.</p>
                        </blockquote>
                        <p>Etiam porta <em>sem malesuada magna</em> mollis euismod. Cras mattis consectetur purus sit amet fermentum. Aenean lacinia bibendum nulla sed consectetur.</p>
                    </div>
                </div>
            </div>
          </div>

      </div>
                    
        
    </body>
</html>

For the end of this tutorial we have to create a function named home while creating this function we will restrict it to logged in users by using login required decorator for that we will import it from django.contrib.auth.decorators

from django.contrib.auth.decorators import login_required

@login_required
def home(request):
    return render(request, 'users/home.html',{'title'"Home"})

Now Let’s create URL pattern for our home page
path('home', app_view.home, name='home'),

Let’s change the after login redirection page to home page in our project settings

LOGIN_REDIRECT_URL = 'home'

Now when the user load our site our login page shows up and after the user logged in our site he will be redirected to home page of our site



Now after creating login system we should not forgot to create logout rout as same as our login rout just need to change login to logout everywhere

path('logout/', authentication.LogoutView.as_view(template_name = 'users/logout.html'), name='logout'),

After that we need to create another file with logout.html name for that we can copy code from home.html we just need to change the heading to You have logged out ! and remove a bunch of those dummy paragraphs
If everything goes right our logout page will look like this



Note: In this tutorial we have not focused on static assets such as HTML and CSS part of our tutorial as our goal was to promote the use of Django framework and creating a User Registration System with it. for those of you who might want to explore template of this tutorial's demo site you can check out my following pens on Code Pen.
  1. Simple Article Styling 
  2. Registration

So, That’s all for this tutorial I hope you might have learn something from this tutorial.

Comments

Popular posts from this blog

Honor Magic 2

What is java ?