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:
- Windows operating system
- Python software version above 3.6,latest version can also be used.
- PostgreSQL Database. Latest version can be used.
- 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:
Check for Python Installation
At the command prompt type python --version
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.
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.
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,
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
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)
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.
- WSGI_APPLICATION = 'company.wsgi.application'
-
-
- DATABASES = {
- 'default': {
- 'ENGINE': 'django.db.backends.sqlite3',
- 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
- }
- }
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.
- WSGI_APPLICATION = 'company.wsgi.application'
-
-
- DATABASES = {
- 'default': {
- 'ENGINE': 'django.db.backends.postgresql_psycopg2',
- 'NAME': 'company',
-
-
-
- 'PORT': '5432',
- }
- }
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.
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
‘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.
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.
To stop running the project and return back to the command prompt, press keys CTRL+ C.
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:
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.
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.
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:
- INSTALLED_APPS = [
- 'employee.apps.EmployeeConfig',
- 'accounts.apps.AccountsConfig',
- 'django.contrib.admin',
- 'django.contrib.auth',
- 'django.contrib.contenttypes',
- 'django.contrib.sessions',
- 'django.contrib.messages',
- 'django.contrib.staticfiles',
- ]
-
-
Add this at the end below lines:
- STATIC_URL = '/static/'
- STATICFILES_DIRS = [os.path.join(BASE_DIR,'static'),]
- STATIC_ROOT =os.path.join(BASE_DIR,'assets')
- MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
- 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
- from django.db import models
- from django.contrib.auth.models import User
-
- class UserProfileInfo(models.Model):
- user = models.OneToOneField(User,on_delete=models.CASCADE)
- username = models.CharField(max_length=25,null=True)
- dob = models.DateField(blank=True,null=True)
- city = models.CharField(max_length=25)
- contactno = models.CharField(max_length=25)
- portfolio_site = models.URLField(blank=True)
- image = models.ImageField(null=True,upload_to='images/', default = 'images/None/no-img.jpg',blank=True)
accounts/models.py File
-
-
- from django.db import models
- from django.urls import reverse, reverse_lazy
-
-
- class Employee(models.Model):
-
- eid = models.AutoField(primary_key=True,serialize = False,verbose_name ='ID')
- ename = models.CharField(max_length=100)
- eemail = models.EmailField()
- econtact = models.CharField(max_length=15)
- edob = models.DateField(blank=True, null=True)
- def get_absolute_url(self):
- return reverse('employee-detail', kwargs={'pk': self.pk})
-
- class Meta:
- db_table = "employee"
- ordering = ['eid',]
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.
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:
The home page of the web application opens as displayed below:
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
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'.
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
If all input data is ok then a new user is created, as shown below.
The new user Alex is successfully logged in and the home page is displayed, as shown below.
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.
When we try to register with the same username, we get the below displayed error message and the registration fails.
Click ‘Login’ and login in ‘Alex’ with the username ‘alex’ and password ’alex1234’.
After a successful login, the home page is displayed below. The user 'Alex' is automatically logged in.
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’.
After a successful login, the Admin link with the drop-down menu can be seen on the navigation bar, as shown below.
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.
A UserProfile Updated successfully message is displayed, as shown below.
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.
Employee Management Page opens, as shown below.
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.
A new Employee Record is created successfully with the pop-up message, as shown below.
The result is displayed on the Employee Management Page, displayed below.
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.
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.
Search the returned two records with the name ‘john’, as shown below.
Click on the eye symbol on the right side to view the record which is displayed below.
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.
All employee records show up, as shown below.
Conclusion
Suggestions for improvement of this tutorial are welcome.
References
- Javapoint.com
- Medium.com
- Django 3.0 documentation
- Stackoverflow .com
- Learndjango.com