Django CRUD And User Authentication With Django Class-Based View And PostgreSQL Database Server

Introduction 

 
This is a simple application to Create, Retrieve, Update and Delete records from a database named 'company', and a table named 'employee' in PostgreSQL Database Server using Django with Django user signup, login, and authentication.
 
Please download the attached files and create the project. If any error write down in the comments section. 
 
Software used in this project:
  1. Windows operating system
  2. Python software version above 3.6,latest version can also be used.
  3. PostgreSQL Database. Latest version can be used.
  4. Django Web Framework software version 3.0.

Install Python

 
If your system is 32 bit then download the Python32bit executable installer. If your system is 64bit then download the Python 64-bit executable installer.
 
To install Python, please follow the tutorial at the below URL
 
https://www.pitt.edu/~naraehan/python3/getting_started_win_install.html
 

Install PostgreSQL Database Server and create a database

 
To install a PostgreSQL database server, follow the tutorial at the below URL(copy & paste in browser)
 
https://medium.com/@9cv9official/creating-a-django-web-application-with-a-postgresql-database-on-windows-c1eea38fe294
 
To create a database named company, please follow the tutorial at the below URL.
 
https://www.guru99.com/postgresql-create-database.html
 
Create a folder named ‘Django3Projects’ in any drive. It is the project folder that I have created in D drive
 
In Windows Explorer, select the folder and shift + right-click. From the dropdown, choose an Open Command Window.
 
Django CRUD And User Authentication With Django Class Based View And Using PostgreSQL Database Server
 

Terminal in Windows 10

 
If you are running newer versions of Windows 10, the command prompt has been replaced by PowerShell. For the examples in this tutorial, the command prompt and PowerShell are functionally the same, and all commands will run in PowerShell unmodified.
 
The command prompt opens, as shown below:
 
Django CRUD And User Authentication With Django Class Based View And Using PostgreSQL Database Server
 

Check for Python Installation

 
At the command prompt type python --version
 
Django CRUD And User Authentication With Django Class Based View And Using PostgreSQL Database Server
 
So system informs that python is installed and version is 3.8.5
 

Creating Virtual Environment in Windows

 
Please type 'python –m venv venv' as, shown below
 
D:\Django3Projects>python -m venv venv
 
Here, m stands for python module and the first venv means module virtual environment
 
The second venv is our newly created virtual environment instance named venv.
 
Django CRUD And User Authentication With Django Class Based View And Using PostgreSQL Database Server
 

Activating Virtual Environment venv

 
Type in venv\scripts\activate at the command prompt to run the newly created virtual environment.venv is the newly created virtual environment instance.
 
Important
 
Always use venv\scripts\activate command at the command prompt to activate the virtual environment if not already activated when opening the project after closing it.
 
Django CRUD And User Authentication With Django Class Based View And Using PostgreSQL Database Server
 

Installing Django Web Framework Version 3.0

 
At the command prompt type pip install django==3.0
 
There are two equal signs before 3.0,
 
Django CRUD And User Authentication With Django Class Based View And Using PostgreSQL Database Server
 

Check installed Django version

 
At the command prompt type python -m django --version
 
Note
Two -- before version
 
Django CRUD And User Authentication With Django Class Based View And Using PostgreSQL Database Server
 

Create a Django project named ‘company’

 
At the command prompt typedjango-admin startproject company
 
Django CRUD And User Authentication With Django Class Based View And Using PostgreSQL Database Server
 
Open the django3 folder. A new folder named company is created as a project folder. Change it into the company folder created in the last step (type cd company at the command prompt)
 
Django CRUD And User Authentication With Django Class Based View And Using PostgreSQL Database Server
 

Creating a Database

 
Django includes several applications by default (e.g., the admin program and user management and authentication). Some of these applications make use of at least one database table, so we need to create tables in the project database before we can use them.
 
Django has sqlite database as the default database, but we want to use the earlier installed PostgreSQL Database server. For that, there would be changes in the database settings inside the settings.py file in the side company directory. Please open the settings.py file.
  1. WSGI_APPLICATION = 'company.wsgi.application'  
  2. # Database  
  3. # https: //docs.djangoproject.com/en/3.0/ref/settings/#databases  
  4.     DATABASES = {  
  5.         'default': {  
  6.             'ENGINE''django.db.backends.sqlite3',  
  7.             'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),  
  8.         }  
  9.     }  
The above database setting is for the default sqlite3 database which ships with Django.
 
We will change it as below so that Django would connect and interact with the earlier installed PostgreSQL database server.
  1. WSGI_APPLICATION = 'company.wsgi.application'  
  2. # Database  
  3. # https: //docs.djangoproject.com/en/3.1/ref/settings/#databases  
  4.     DATABASES = {  
  5.         'default': {  
  6.             'ENGINE''django.db.backends.postgresql_psycopg2',  
  7.             'NAME''company',  
  8.             #use your database name here at the time of creation 'USER': 'raichand70',  
  9.             #use your database username here at the time of creation 'PASSWORD': '1canada',  
  10.             #use your database password here at the time of installation 'HOST': 'localhost',  
  11.             'PORT''5432',  
  12.         }  
  13.     }   
Then save the settings.py file.
 

Psycopg 

 
Psycopg is a PostgreSQL adapter for the Python programming language. It is used to connect to and interact with PostgreSQL Database Server from Python Programming language.
 
Installing Psycopg
 
Type pip install Psycopg2 at command prompt and execute
 
Django CRUD And User Authentication With Django Class Based View And Using PostgreSQL Database Server
 
To display a message, the pyautogui module of python is used
 
Type pip install pyautogui at the command prompt and execute.
 
Django CRUD And User Authentication With Django Class Based View And Using PostgreSQL Database Server

To manage images(Image Upload etc) Pillow module has to be installed. Pillow is built on top of PIL (Python Image Library). PIL is one of the important modules for image processing in Python Type pip install Pillow at command prompt and press enter to execute it as shown below.

 
To create databases, run the following commands on the command prompt, as shown below.
 
python manage.py makemigrations
python manage.py migrate
 
Django CRUD And User Authentication With Django Class Based View And Using PostgreSQL Database Server
 
‘No migrations to apply.’ As the company database with tables was already created earlier.
 
Start the development server to verify your project work by executing python manage.py runserver at the command prompt.
 
Django CRUD And User Authentication With Django Class Based View And Using PostgreSQL Database Server
 
Click on the http://127.00.1:8000/ link in the above window or copy and paste in the browser. If the below page opens in your default browser, then the project is created successfully.
 
Django CRUD And User Authentication With Django Class Based View And Using PostgreSQL Database Server
 
To stop running the project and return back to the command prompt, press keys CTRL+ C.
 
Django CRUD And User Authentication With Django Class Based View And Using PostgreSQL Database Server
 

Create SuperUser(Admin) for the website

 
At the command prompt type ‘python manage.py createsuperuser ‘
 
Enter your desired username and press enter.
 
Username: admin
Django will then prompt you for your email address:
Email address: admin@example.com
 
The final step is to enter your password. Django asks you to enter your password twice; the second time as a confirmation of the first.
 
Password: **********
Password (again): *********
Superuser created successfully.
 
I entered ‘admin1234’ as password for the project.
 
Now you have created an admin user, you’re ready to use the Django admin.
 

Create Two apps named ‘employee’ and ‘accounts’

 
At the command prompt type python manage.py startapp employee to create employee app. Then execute the command by pressing the ‘enter’ key.
 
At the command prompt type python manage.py startapp accounts to create accounts app. Then execute command by pressing the ‘enter’ key.
 
Django CRUD And User Authentication With Django Class Based View And Using PostgreSQL Database Server
 
The accounts app would be used for user management (SignUp, Login, Logout, etc) of the website. An employee app would be used to manage employees.
Inside the Company folder as shown below create three folders named ‘media, ‘static, and ‘templates’. Inside the employee folder, create a folder named ‘templates’, which would store templates used in the employee app.  
 
Django CRUD And User Authentication With Django Class Based View And Using PostgreSQL Database Server
 
Similarly, add a folder named 'templates’ inside the accounts folder, which would store templates used in the accounts app. Inside the created templates folder, create another folder named registration folder, as shown below.
 
Django CRUD And User Authentication With Django Class Based View And Using PostgreSQL Database Server
 
Create a folder named ‘None’ inside media/images as shown below and place ‘no-img’ picture inside it as shown below
 

The ‘no-img’ picture is shown below. It would be displayed in the profile page if the profile image is not uploaded by the user or admin.

 
Changes in the settings.py file in the company folder:
  1. INSTALLED_APPS = [  
  2.    'employee.apps.EmployeeConfig'# Adding The Employee app #new  
  3.    'accounts.apps.AccountsConfig'# Adding The accounts app #new  
  4.    'django.contrib.admin',  
  5.    'django.contrib.auth'#Module to for user login,logout etc processes  
  6.    'django.contrib.contenttypes',  
  7.    'django.contrib.sessions',  
  8.    'django.contrib.messages',  
  9.    'django.contrib.staticfiles',  
  10. ]  
  11. # Static files (CSS, JavaScript, Images)  
  12. # https://docs.djangoproject.com/en/3.1/howto/static-files/  
Add this at the end below lines:
  1. STATIC_URL = '/static/'  
  2. STATICFILES_DIRS = [os.path.join(BASE_DIR,'static'),]  
  3. STATIC_ROOT =os.path.join(BASE_DIR,'assets')  
  4. MEDIA_ROOT = os.path.join(BASE_DIR, 'media')  
  5. MEDIA_URL = '/media/'   
 

Create a python file named ‘views.py’ inside the company folder as shown below, which would contain class-based views to display the web page like the front page.

 
 
 
 

---------- --------------------------------views.py ------------------------------------

from django.urls import reverse,reverse_lazy

from django.views.generic import TemplateView

# Create your views here.

class HomePageView(TemplateView):#Displays home or front page.

template_name = 'index.html'

-------------------------------------------------------------------------------------------

 
Create three python files urls.py,models.py and forms.py inside employee folder and create another three python files urls.py,models.py and forms.py inside the accounts folder.
 
I have created models in themodels.py files in accounts and the employee app.
 
employee/models.py File
  1. from django.db import models  
  2. from django.contrib.auth.models import User  
  3. # Create your models here.  
  4. class UserProfileInfo(models.Model):  
  5. user = models.OneToOneField(User,on_delete=models.CASCADE)  
  6. username = models.CharField(max_length=25,null=True)  
  7. dob = models.DateField(blank=True,null=True# If no date is selected then Django saves blank field value.  
  8. city = models.CharField(max_length=25)  
  9. contactno = models.CharField(max_length=25)  
  10. portfolio_site = models.URLField(blank=True)  
  11. image = models.ImageField(null=True,upload_to='images/', default = 'images/None/no-img.jpg',blank=True)  
accounts/models.py File
  1. # import the standard Django Model  
  2. # from built-in library  
  3. from django.db import models  
  4. from django.urls import reverse, reverse_lazy  
  5. # Create your models here.  
  6. # declare a new model with a name"employee"  
  7. class Employee(models.Model):  
  8. # fields of the model  
  9. eid = models.AutoField(primary_key=True,serialize = False,verbose_name ='ID')  
  10. ename = models.CharField(max_length=100)  
  11. eemail = models.EmailField()  
  12. econtact = models.CharField(max_length=15)  
  13. edob = models.DateField(blank=True, null=True)# If no date is selected then Django saves blank field value.  
  14. def get_absolute_url(self):  
  15. return reverse('employee-detail', kwargs={'pk'self.pk})  
  16. #objects = models.Manager()  
  17. class Meta:  
  18. db_table = "employee"  
  19. ordering = ['eid',]#sorts the records ascending using 'eid' field   
We have created two new models so the corresponding tables are to be created in company database. Run two commands - python manage.py makemigrations and python manage.py migrate at the command prompt, as shown below.
 
Django CRUD And User Authentication With Django Class Based View And Using PostgreSQL Database Server
 
UserprofileInfo Table in the company database is created in the PostgreSQL database server, as shown below.
 
Django CRUD And User Authentication With Django Class Based View And Using PostgreSQL Database Server

  1. ---------------------------------------base.html-------------------------------------------------  
  2. <!doctype html>  
  3. {% load static %}  
  4. <html lang="en"><head>  
  5. <!-- Required meta tags -->  
  6. <meta charset="utf-8">  
  7.     <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">  
  8.         <!-- Bootstrap CSS -->  
  9.         <link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css" rel="stylesheet"/>  
  10. {% block title %}  
  11. {% endblock title %}  
  12.     </head>  
  13.     <body>  
  14.         <!-- Optional JavaScript -->  
  15.         <!-- jQuery first, then Popper.js, then Bootstrap JS -->  
  16.         <link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet"/>  
  17.         <!-- Bootstrap -->  
  18.         <script src ="https://code.jquery.com/jquery-3.3.1.min.js"></script>  
  19.         <script src ="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>  
  20.         <!--Navbar Starts Here-->  
  21.         <nav class="navbar navbar-expand-lg navbar-light bg-light mb-4">  
  22.             <a class="navbar-brand" href="{% url 'home' %}">RelianceIndustries</a>  
  23.             <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">  
  24.                 <span class="navbar-toggler-icon"></span>  
  25.             </button>  
  26.             <div class="collapse navbar-collapse" id="navbarSupportedContent">  
  27.                 <ul class="navbar-nav mr-auto">  
  28.                     <li class="nav-item active">  
  29.                         <a class="nav-link" href="{% url 'home' %}">Home   
  30.                             <span class="sr-only">(current)</span>  
  31.                         </a>  
  32.                     </li>  
  33.                     <li class="nav-item active">  
  34.                         <a class="nav-link" href="{% url 'about' %}">About   
  35.                             <span class="sr-only">(current)</span>  
  36.                         </a>  
  37.                     </li>  
  38.                     <li class="nav-item active">  
  39.                         <a class="nav-link" href="{% url 'services' %}">Services   
  40.                             <span class="sr-only">(current)</span>  
  41.                         </a>  
  42.                     </li>  
  43.                     <li class="nav-item active">  
  44.                         <a class="nav-link" href="{% url 'contact' %}">Contact  
  45.                             <span class="sr-only">(current)</span>  
  46.                         </a>  
  47.                     </li>  
  48.                 </ul>  
  49.   
  50. {% if user.is_authenticated and user.is_superuser %}  
  51.   
  52.   
  53.                 <ul class="navbar-nav">  
  54.                     <li class="nav-item dropdown">  
  55.                         <a class="nav-link dropdown-toggle" href="#" id="navbarDropdown1" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">  
  56.   
  57. Admin  
  58.   
  59. </a>  
  60.                         <div class="dropdown-menu" aria-labelledby="navbarDropdown">  
  61.                             <a class="dropdown-item" href="#">Action</a>  
  62.                             <a class="dropdown-item" href="{%url 'profile' pk=user.userprofileinfo.id %}" id='get' onlick='document.getElementById(this.id).removeAttribute("href");' >Profile</a>  
  63.                             <a class="dropdown-item" href="{% url 'employees-list' %}" >EmployeeManager</a>  
  64.                             <a class="dropdown-item" href="#">Another action</a>  
  65.                             <div class="dropdown-divider"></div>  
  66.                             <a class="dropdown-item" href="{% url 'logout' %}">Logout</a>  
  67.                         </div>  
  68.                     </li>  
  69.                 </ul>  
  70.   
  71. {% elif user.is_authenticated %}  
  72.   
  73.   
  74.                 <ul class="navbar-nav">  
  75.                     <li class="nav-item dropdown">  
  76.                         <a class="nav-link dropdown-toggle" href="#" id="navbarDropdown2" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">  
  77.   
  78. {{request.user.first_name}}  
  79.   
  80. </a>  
  81.                         <div class="dropdown-menu" aria-labelledby="navbarDropdown">  
  82.                             <a class="dropdown-item" href="#">Action</a>  
  83.                             <a class="dropdown-item" href="{%url 'profile' pk=user.userprofileinfo.id %}" id='profile' onlick='document.getElementById(this.id).removeAttribute("href");'>Profile</a>  
  84.                             <div class="dropdown-divider"></div>  
  85.                             <a class="dropdown-item" href="{% url 'logout' %}">Logout</a>  
  86.                         </div>  
  87.                     </li>  
  88.                 </ul>  
  89.   
  90. {% else %}  
  91.   
  92.   
  93.                 <a class="btn btn-outline-secondary" href="{% url 'login' %}">Login</a>  
  94.                 <a class="btn btn-primary ml-2 mr-2" href="{% url 'sign-up' %}">SignUp</a>  
  95.   
  96. {% endif %}  
  97.   
  98.   
  99.                 <form class="form-inline my-2 my-lg-0" action="#" method='GET'>  
  100.                     <input class="form-control mr-sm-2" type="search" name='q' aria-label="Search" placeholder='Search' value={{request.GET.q}} >  
  101.                         <button class="btn btn-outline-success my-2 my-sm-0" type="submit">Search</button>  
  102.                     </form>  
  103.                 </div>  
  104.             </nav>  
  105.             <!--Navbar Ends-->  
  106. {% block content %}  
  107. {% endblock content%}  
  108.         </body>  
  109.     </html>  
  110.   
  111.  -----------------------------------------------------------------------------------------------------------------------------------------------------------   

 

In the company database, the employee table is also created and displayed below in Tables.
 
To run the web application and start the development server, execute the below commands at the command prompt, as displayed below:
 
Django CRUD And User Authentication With Django Class Based View And Using PostgreSQL Database Server
 
The home page of the web application opens as displayed below:
 
Django CRUD And User Authentication With Django Class Based View And Using PostgreSQL Database Server
We have already created Admin(superuser) before, and we will create a user with the username 'alex' and password 'alex1234'. At first, we will give a different password for 'confirm password'. An error message will pop up, and the sign up will fail.
 
Click on the SignUp button to register a new user with username 'alex'. The register page opens
 
Django CRUD And User Authentication With Django Class Based View And Using PostgreSQL Database Server
 
Django CRUD And User Authentication With Django Class Based View And Using PostgreSQL Database Server
 
Choose a date from the opened date picker and click the signup button. It gives an error message and registration is not successful as shown below as we had given different password values for 'Password' and 'Confirm Password'.
 
Django CRUD And User Authentication With Django Class Based View And Using PostgreSQL Database Server
 
If we try to sign up with an already registered username and email id error message would be displayed and the user would not be registered.
 
Now we try again with password 'alex1234' and confirm password 'alex1234' as shown below
 
Django CRUD And User Authentication With Django Class Based View And Using PostgreSQL Database Server
 
If all input data is ok then a new user is created, as shown below.
 
Django CRUD And User Authentication With Django Class Based View And Using PostgreSQL Database Server
 
The new user Alex is successfully logged in and the home page is displayed, as shown below.
 
Django CRUD And User Authentication With Django Class Based View And Using PostgreSQL Database Server
 
Click Log out from drop-down menu with ‘Alex’ Link to log out. Then click the signup button.
 
When we try to register with the same email address, we get the below error message and the registration fails.
 
Django CRUD And User Authentication With Django Class Based View And Using PostgreSQL Database Server
 
When we try to register with the same username, we get the below displayed error message and the registration fails.
 
Django CRUD And User Authentication With Django Class Based View And Using PostgreSQL Database Server
 
Click ‘Login’ and login in ‘Alex’ with the username ‘alex’ and password ’alex1234’.
 
Django CRUD And User Authentication With Django Class Based View And Using PostgreSQL Database Server
 
After a successful login, the home page is displayed below. The user 'Alex' is automatically logged in.
 
Django CRUD And User Authentication With Django Class Based View And Using PostgreSQL Database Server

  1. ----------------------------------------userprofile.html--------------------------------------------  
  2. {% extends 'base.html' %}  
  3. {% block title %}  
  4. <title>Profile</title>  
  5. {% endblock title %}  
  6. {% block content %}  
  7. <!--<script src ="https://code.jquery.com/jquery-3.3.1.min.js"></script>-->  
  8. <script src ="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script>  
  9. <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">  
  10.     <script src="https://code.jquery.com/jquery-1.12.4.js"></script>  
  11.     <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>  
  12.     <form method="POST" class="post-form" enctype="multipart/form-data" >  
  13. {% csrf_token %}  
  14.         <div class="container">  
  15.         
  16.             <img src ="{{ user.userprofileinfo.image.url }}"  
  17.   
  18. class = "img-fluid rounded-circle" alt = "Responsive Image" width = "175" height = "175">  
  19. {% if user.is_authenticated and user.is_superuser %}  
  20.                 <h1>  
  21.                     <strong>Welcome Admin </strong>  
  22.                 </h1>  
  23.   
  24. {% else %}  
  25.                 <h1>  
  26.                     <strong>Welcome {{user.first_name}}</strong>  
  27.                 </h1>  
  28. {% endif %}  
  29.                 <h2> Update Profile Page</h2>  
  30.                 <br>  
  31.                     <div class="form-group row">  
  32.                         <div class="col-sm-4">  
  33.                             <input type="hidden" name="username" id="id_username" required maxlength="15" value="{{user.username }}" />  
  34.                         </div>  
  35.                     </div>  
  36.                     <div class="form-group row">  
  37.                         <label class="col-sm-3 col-form-label">Id:</label>  
  38.                         <div class="col-sm-4">  
  39.                             <label>{{ user.id }} </label>  
  40.                         </div>  
  41.                     </div>  
  42.                     <div class="form-group row">  
  43.                         <label class="col-sm-2 col-form-label"> City:</label>  
  44.                         <div class="col-sm-4">  
  45.                             <input type="text" name="city" id="id_city" required maxlength="15" value="{{user.userprofileinfo.city }}" />  
  46.                         </div>  
  47.                     </div>  
  48.                     <div class="form-group row">  
  49.                         <label class="col-sm-2 col-form-label">Contact No:</label>  
  50.                         <div class="col-sm-4">  
  51.                             <input type="text" name="contactno" id="id_contactno" required maxlength="15" value="{{ user.userprofileinfo.contactno }}" />  
  52.                         </div>  
  53.                     </div>  
  54.                     <div class="form-group">  
  55.                         <label for="id_dob"> Date of Birth:     </label>  
  56.                         <input type="text" name="dob" id="id_dob" required maxlength="25" value="{{ user.userprofileinfo.dob }}" aria-describedby="passwordHelpInline">  
  57.                             <span class="input-group-addon">  
  58.                                 <i class="fa fa-calendar fa-lg"></i>  
  59.                             </span>  
  60.                             <big id="textHelpInline" class="text-muted">  
  61.   
  62. Date Must be YYYY-MM-DD Format.  
  63.   
  64. </big>  
  65.                         </div>  
  66.                         <div class="form-group row">  
  67.                             <label class="col-sm-2 col-form-label">{{user.first_name}} Picture:</label>  
  68.                             <div class="col-sm-4">  
  69.   
  70. {{ form.image}}  
  71.   
  72. </div>  
  73.                         </div>  
  74.                         <div class="form-group row">  
  75.                             <label class="col-sm-2 col-form-label"></label>  
  76.                             <div class="col-sm-4">  
  77.                                 <button type="submit" class="btn btn-info">Update</button>  
  78.                                 <a href="/" class="btn btn-info">Cancel</a>  
  79.                             </div>  
  80.                         </div>  
  81.                     </div>  
  82.                 </form>  
  83. {% block scripting %}  
  84.                 <script>  
  85. $( function() {  
  86.    $( "#id_dob" ).datepicker({  
  87.       changeMonth: true,  
  88.       changeYear: true,  
  89.       yearRange: '1950:2050',  
  90.       dateFormat: 'yy-mm-dd',  
  91.       defaultDate:"24-09-2019"  
  92.    });  
  93. } );  
  94. </script>  
  95.                 <script>  
  96.    $(document).ready(function () {  
  97.       $('.dropdown-toggle').dropdown();  
  98.       });  
  99.    </script>  
  100. {% endblock %}  
  101. {% endblock content %}  
  102. -------------------------------------------------------------------------------------------------------    

 

After signing in from the Alex link drop-down menu, click ‘Profile’ to view and update user Alex’s profile, as shown below.
 
Django CRUD And User Authentication With Django Class Based View And Using PostgreSQL Database Server
 
 
Django CRUD And User Authentication With Django Class Based View And Using PostgreSQL Database Server
 
Similarly, the Admin (superuser) would log in with username ‘admin’ and password ‘admin1234’.
 
Django CRUD And User Authentication With Django Class Based View And Using PostgreSQL Database Server
 
After a successful login, the Admin link with the drop-down menu can be seen on the navigation bar, as shown below.
 
Django CRUD And User Authentication With Django Class Based View And Using PostgreSQL Database Server
 
Click on the profile menu item of the dropdown menu for Admin Link. As shown below. Fill up the Blank Fields,upload profile picture and Choose a date from the date picker for the ‘Date of Birth’ field. Click the Update button.
 
Django CRUD And User Authentication With Django Class Based View And Using PostgreSQL Database Server
 
A UserProfile Updated successfully message is displayed, as shown below.
 
Django CRUD And User Authentication With Django Class Based View And Using PostgreSQL Database Server

Updated profile page of ‘Admin’ is displayed below.

 
 

Managing Employees through Employee App from Admin Menu

 
After Logging in with admin username 'admin' and password 'admin1234' in Admin Dropdown Menu, click the Employee Manager link, as shown below.
 
Django CRUD And User Authentication With Django Class Based View And Using PostgreSQL Database Server
 
Employee Management Page opens, as shown below.
 
Django CRUD And User Authentication With Django Class Based View And Using PostgreSQL Database Server
 
There is no employee record in the employee table, so it doesn't display any record
 
Click on the Add New button to add a new employee record as shown below and click the Create Button.
 
Django CRUD And User Authentication With Django Class Based View And Using PostgreSQL Database Server
 
A new Employee Record is created successfully with the pop-up message, as shown below.
 
Django CRUD And User Authentication With Django Class Based View And Using PostgreSQL Database Server
 
The result is displayed on the Employee Management Page, displayed below.
 
Django CRUD And User Authentication With Django Class Based View And Using PostgreSQL Database Server
 
Similarly, add 15 more new employee records so that 5 records per page would be displayed on the Employee Management System Page.
 
After adding records, the Employee Management System Page is shown below.
 
Django CRUD And User Authentication With Django Class Based View And Using PostgreSQL Database Server
 

Searching Employee From Name part

 
To search the employee, enter part of the name ‘john’ in the search box, then click the Search button, as shown below.
 
Django CRUD And User Authentication With Django Class Based View And Using PostgreSQL Database Server
 
Search the returned two records with the name ‘john’, as shown below.
 
Django CRUD And User Authentication With Django Class Based View And Using PostgreSQL Database Server
 
Click on the eye symbol on the right side to view the record which is displayed below.
 
Django CRUD And User Authentication With Django Class Based View And Using PostgreSQL Database Server
 
Click on the ok button to go back to the Employee Management System Page. Then click on the pencil symbol on the right side to edit the record. The Update page is displayed below. We will make corrections in Employee Name and Employee Email and click the update button to update the corresponding record.
 
Django CRUD And User Authentication With Django Class Based View And Using PostgreSQL Database Server
 
The updated page is displayed below. Click the Update button to update the record. An Update successful message pops up.
 
Django CRUD And User Authentication With Django Class Based View And Using PostgreSQL Database Server
 
The updated record is shown below.
 
Django CRUD And User Authentication With Django Class Based View And Using PostgreSQL Database Server

Class Based view ‘UpdateView’ is displayed below

------------------------------------------------------------------------

# Only logged in superuser can see this view

Class employeeUpdateView(

LoginRequiredMixin,UserPassesTestMixin,UpdateView):

model = Employee

template_name = 'update.html'

# specify the fields

fields = ['eid', 'ename', 'eemail', 'econtact', 'edob']

login_url = 'login' #if not authenticated redirect to login page

# only superuser is allowed to see this view.

def test_func(self):

return self.request.user.is_superuser

# updating details

# url to redirect after successfully updation

def get_success_url(self):

# Displaying message of successful updation of employee

pu.alert(text='Employee Info Updated Successfully', title='Update', button='OK')

return reverse_lazy('employees-list')

------------------------------------------------------------------------------

LoginRequiredMixin:-This parameter restrict only logged in user can see the view.

UserPassesTestMixin:-This parameter restrict only Superuser can see the view.

To know about Mixin please go to webpage at below URL.

https://docs.djangoproject.com/en/3.0/topics/class-based-views/mixins/

 
 
Click on the red colored trash bin button on the right-hand side to delete the record. The delete record page opens as shown below.
 
Django CRUD And User Authentication With Django Class Based View And Using PostgreSQL Database Server
 
Click on the Delete button to delete the record and the ‘Employee Deleted Successfully’ message pops up.
 
Django CRUD And User Authentication With Django Class Based View And Using PostgreSQL Database Server
 
All employee records show up, as shown below.
 
Django CRUD And User Authentication With Django Class Based View And Using PostgreSQL Database Server
 

Conclusion 

 
Suggestions for improvement of this tutorial are welcome.
 
References
  1. Javapoint.com
  2. Medium.com
  3. Django 3.0 documentation
  4. Stackoverflow .com
  5. Learndjango.com