Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Django

Download as pdf or txt
Download as pdf or txt
You are on page 1of 139

Table of Contents

Part -1 (Introduction) .........................................................................................................................................................


Part -2 (Software’s Installation) ........................................................................................................................................
Part - 3(MVT Pattern).........................................................................................................................................................
Part – 4 (Create and run first Django project)...................................................................................................................
Part -5 (Creating applications and views under)...............................................................................................................
Part -6 (Working with multiple applications)....................................................................................................................
Part – 7 (Application-level URL mappings)........................................................................................................................
Part – 8 (Creating templates).............................................................................................................................................
Part – 9 (Sending data from view to template) ................................................................................................................
Part – 10 (Inserting images into templates) ......................................................................................................................
Part – 11(Linking stylesheets with templates) ..................................................................................................................
Part – 12 (Set homepage with links in Django project) ....................................................................................................
Extra session (Database Management System basics for database connectivity) ..........................................................
Part – 13 (Introduction to models) ....................................................................................................................................
Part – 14 (Creating models) ...............................................................................................................................................
Part – 15 (Using models in views) .....................................................................................................................................
Part – 16 (Django MySQL connectivity).............................................................................................................................
Part – 17 (Django Admin UI) ..............................................................................................................................................
Part – 18 (Django ORM Part-1) ..........................................................................................................................................
Part – 19 (Django ORM Part-2) ..........................................................................................................................................
Part - 20 (Model Forms in Django) ....................................................................................................................................
Part – 21 (Saving form data into database) ......................................................................................................................
Part – 22 (How to create HTML forms using Django forms) .............................................................................................
Part – 23 (CRUD Operations with function-based views) .................................................................................................
Part – 24 (Class Based Views) ............................................................................................................................................
Part – 25 (CRUD Operations using Class based views) .....................................................................................................
Part – 26 (Authentication in Django).................................................................................................................................
Part – 27 (Authorization in Django)...................................................................................................................................
Part – 28 (Session Management in Django) ......................................................................................................................
Part -1 (Introduction)
What are web applications:

• The applications which is accessible by browser like chrome, Firefox etc.…


are called web applications.
• For example, a Gmail we can access Gmail but we are not installed any Gmail
software file in our local system.
• We can use many technologies to develop web applications but here we are
using python (Django) to develop web applications.

Client – server model:

Different roles to develop web applications:

1. Web Designer
• His responsibilities are to design our web page to visit our clients
again and again.
• We designer just give a blue print of web page.
• Roles in web design are like UI/UX developer
2. Web Developers
• Web developer will start real work to build a web site.
• Roles are like frontend developer, backend developer etc.
Real example:

• We will have architect and builder will be there to build a building.


• Here we can say architect as web designer and builder as a web developer.
• So here architect design house and builder will build house.

What is use Django:


• This is python web framework.
• By using this we can create a web page very fast.
• We don’t need to write code from scratch we just need to write an essential
code only.
• We will get inbuilt web server for practice purpose.

Part -2 (Software’s Installation)


Required software’s:
• Python
• Django
• IDE
• MySQL

Note: I have installed all these so skipping this tutorial.


Part - 3(MVT Pattern)
Workflow diagram:

Workflow of Django:
• First all requests will go for Django server by using a URL.
• These each URL having one respective view, that will call when that URL is
called.
• Based on view it will take data from models if data required and then
response to user using templates.

Real time example:


Part – 4 (Create and run first Django project)
Django project structure:

• Within project, you have multiple app’s which is used for particular task.
• Collection of apps or single app is called Django project.

Creating and running first project:

• Command to create a project: django-admin startproject first


• Command to run a project : python manage.py runserver <Port Number>
• And explanation about all files in project.
Part -5 (Creating applications and views under)
Workflow of project:

• Whenever a user enters a URL in browser that URL will call one views which
will have logic.
• Based on logic in views if required it will call models (database) and fetch
data and send to respective template.

Steps:

1. Create an application (app)


2. Adding this app in setting.py file.
3. Create a respective view (function based /class based)
4. Link views with respective urls.py file
5. Run project.

Creating first Django project with app:


1. Create an application (app)
• Django-admin startproject SchoolPro → Project Creation
• python manage.py startapp Admissions → App Creation
2. Adding this app in setting.py file.
3. Create a respective view (function based /class based)

Views can create in two ways, they are


1. Function based views
• Every function is view.py is consider as a single view in function-based
views
2. Class based views
• Every class in view.py is consider as a single view in function-based
views
Note: Now we are using function-based views next coming sessions we will learn
class-based views.
Views in Django:

• Every view in function-based views is take request as a parameter and


respond based on request.
• Code is written below

4. Link views with respective urls.py file


• Linking all URLs with respective to views.

5. Run project
• py manage.py runserver
• http://127.0.0.1:8000/newadm/


• http://127.0.0.1:8000/viewadms/

Note : Instead of this simple message we can also render a template i.e. html page.
Part -6 (Working with multiple applications)

Adding another app to our pervious project: python manage.py startup finance
Finance/views.py :

Now we need to write URLs for each view to access this view.

Urls.py :
Output :

All URLs are working fine.

Note : we might get same some errors when we are including all apps URLs in one
main project urls.py file. So, we will maintain and see next video how to maintain
URLs at app level.

Part – 7 (Application-level URL mappings)


For this we need to create urls.py file in all app level structure then we need to
include this at main project urls.py file.

Let’s create those individual urls.py files below :


Schoolpro/urls.py :

Output :

All below URLs are working fine means we are good with multiple urls.py files.
http://127.0.0.1:8000/finance/feecol/
http://127.0.0.1:8000/finance/duereport/
http://127.0.0.1:8000/finance/colreport/

http://127.0.0.1:8000/admissions/newadm/
http://127.0.0.1:8000/admissions/viewadms/

Part – 8 (Creating templates)


Note : in our previous classes we have only seen how to send a simple message
and also, we can write HTML code with that response but writing html code in that
double quotes is not good practice. To show total web page we use concept called
templates.
Steps to create a template :

1. Create template folder


2. Adding this DIR in settings.py file.
3. Creating templates/html in template folder.
4. Use template in views
5. Running server testing functionality

1. Create template folders:

• Need to create a template folder at project level


2. Adding templates in settings.py file :
3. Creating templates/html in template folder :

Now creating a html/template like below:

4. Use template in views


5. Output :

Note: Now we are getting data from templates not from HTTP Response. So,
create templets for finance app also and test those.

Django Template Inheritance:


Template Inheritance is a method to add all the elements of an HTML file into another without
copy-pasting the entire code. For example, consider the Facebook homepage. Here the
underlying theme of the web page; background, elements, etc., are same for all FB endpoints

There are two ways to achieve this:


✓ Add the same CSS/JS/HTML code all the Endpoint Templates
✓ OR, create a single file containing all common elements and then simply include it in
others.
The second method is what exactly the Template Inheritance does.

Why Inheritance?
✓ Just like Facebook, most of the Applications have long HTML codes for a single page
itself. Now to write all that again and again for every page is not possible and a very
inefficient method.
✓ Thus, Django provides the method of Template inheritance to ensure more efficiency
and less repetition of code.

✓ Another significant benefit with Template inheritance is that, if we modify the main file,
it will automatically get changed at all places where it was inherited. Thus we don’t need
to modify it at all other places

Practical:

Let’s create a project from scratch:

1.Create a project :-
django-admin startproject TempInheritance

2.Create a app :-
py manage.py startapp app

3.Add this app into installed apps and create a template folder and do settings in settings.py
file.
Create 3 urls and respective views and repective html pages.

Including app urls in main project urls:

Create 3 views and respective urls and templates:

Views.py :

Urls.py:

Templates:
Sample1.html

Sample2.html

Sample3.html
Outputs:

Add Home page now:


Output:

Note: I have added nav bar to home page. But this nav bar will show only home page. But as
per every website we should have same nav bar. In this we will use template inheritance to
reuse that nav bar code. For that follow below steps.

Steps to implement template inheritance:


1. Create a base.html file with below tags.

<title> {% block title %} dynamic titile {% endblock %} <title>


{% block content %} Dynamic text{% endblock %}

2. Use extends method at every child html page.

{% extends "base.html" %}

Create a base template like below:


Use base.html in home page and every page:
Note : change block title and block contant as per requirement.

Templates pages:
Output:
Part – 9 (Sending data from view to template)
In this tutorial , we can see how to send a data from views to template. This will
also same when we are working with models (database) also.

Views.py :
Output :
Part – 10 (Inserting images into templates)
In this tutorial, we will see how to add static file like images,css,js etc.

Steps to work with static files :

1. Create static folder


2. Add this in static in settings.py file.
3. Create required folders and static files in static folder.
4. Load the static files ( {% load static %} )
5. Add image now
6. Output

1. Create static folder :

• Just create folder same like templates folder.


2. Add this in static in settings.py file.
3. Create required folders and static files in static folder.

4. Load the static files and adding image:


6. Output
Note : In old document they mentioned as a {% load static file %} instead of {%
load static %} . So, need to use updated one only.

Part – 11(Linking stylesheets with templates)

For adding CSS also, we will follow below steps:

• After creating a CSS file in CSS folder in static folder.

• Link style sheet like below in template :

• Then write CSS in CSS file :


• Output
Part – 12 (Set homepage with links in Django project)
In this tutorial we are going to create a home page where we have all links for
these URLs. Reason is we can’t remember all URLs so we need to create link for all
options like below.

Create a view , URL and template for home page :

View :

URL :
Template :

Planning for this home page :


Let’s code for that home page :
Html code:

Style.css:
Output:
Extra session (Database Management
System basics for database connectivity)
Database : Database is nothing but a system which will allow us to insert and retire
database quickly and easily.

Database management system : Nothing but a managing of databases.


Types of DBMS :
1. Relational database.
2. Object oriented database.
3. Hierarchical database.
4. Network database.
We are going to discuss about Relational Database Management System.(RDBMS)
In RDBMS data will be stored in the forms of tables means we will have columns
and rows.
Queries : Queries are special instructions which will be useful to fetch and store
data in database.
SQL → Structure query language is useful to write a query to do any operations I
in RDBMS .

Types of RDBMS :
• MySQL
• PostgreSQL
• Microsoft SQL Serve
• Oracle Database.
Note : Here we are using MySQL as our database for practice. As it was a open
source software.

Working with MySQL :


Do installation by using any video in YouTube.
Then open cmd and type like “mysql -u root -p”

We are working with school project so let’s create school database using below
command :
Create database school;
Drop database school;

Tables operations :
1. Create table and insert data

Syntax:
CREATE TABLE table_name (
column1 datatype,
column2 datatype,
column3 datatype,
....
);

Example :
Create table Student(
RNO int,
Name varchar(200),
Class varchar(100)
);

Practical implementation:
Inserting data :
Insert into student values(1,’rakesh’,’A’);

Practical implementation :

2. Read table
Syntax :

Select * from table name;

3. Update table
4. Delete table

Part – 13 (Introduction to models)


Models :
• Models means data base in MVT architecture.
• Generally, each model maps to a single database table.
• In ORM , instead of working with database quires we will work with models
to get data and store data from database.
• By default, database in Django model is SQLite.
Syntax to create a model in Django:

Class Student (models.Model):


Fields.
…..
Note : We can create multiple models based on our requirement. These models
we need to create in model.py file only.

After creating model, we need to register those models in admin.py file to get
show in admin page.

Commands to run models :

• python manage.py makemigrations


o This will create a migration file which will have quires related to
database.
• python manage.py migrate
o Now we are executing that migrate file into database.

Part – 14 (Creating models)


In Our project we need a database called “student” with columns like name, father
name, class and contact etc.
Note : In other language we need to write a SQL query to create database but
when we are using Django ORM, we don’t need to create SQL quires separately.

Steps :

1. Adding database settings in setting.py file.


2. Write models in model.py file
3. Do model migrations
To see SQL query :

• python manage.py sqlmigrate <app name> <file name>


• python manage.py sqlmigrate Admissions 0001

How to check table created or not using shell :

Part – 15 (Using models in views)


Summary :

• How get all records from model(table)


• How to insert records from shell console.

Inserting records into table by using shell :


Now working in views to get data into template :
Views.py :

Template :
Output :
Creating a way if there is no records then it should show “no
records found error”.
1 <h1>Hello, List of all adimissions in this school</h1>
2 {% if students %}
3 <table border="1">
4 <tr>
5 <th>Student Name</th>
6 <th>Father Name</th>
7 <th>Class Name</th>
8 <th>Contact Number</th>
9 </tr>
10 {% for student in students %}
11 <tr>
12 <td>{{student.name}}</td>
13 <td>{{student.father_name}}</td>
14 <td>{{student.st_class}}</td>
15 <td>{{student.contact}}</td>
16 </tr>
17 {% endfor %}
18 </table>
19 {% else %}
20 <h1>No Records found</h1>
21 {% endif %}

Output :
Now no record in database so output like below:

After inserting records into table:


Part – 16 (Django MySQL connectivity)

Need to change setting.py file :


Default settings:

MySQL settings:
Note : if we are running local host then it no required to “Host” and “Port”.

Checking connection and tables:

Tables after doing migrations:


Note : But we usually wont use “root” user to work with application. Reason if
our application hacked then total database will get hacked.

Creating separate user :

Now testing connection using SQL work bench:


Note : Now user connected only that particular database.

Now changing application user settings:

Now Able to access database:


Some MYSQL user related quires :

Create new user in MySQL:


CREATE USER 'SchoolAppUser'@'localhost' IDENTIFIED BY 'Rakhi5699';

Show all users in MySQL database:


SELECT * from mysql.user; / SELECT user from mysql.user;

To see current user logged in:


SELECT user(); / SELECT current_user();

To drop user:
DROP USER 'SchoolAppUser'@'localhost';

Grant all privileges to user;


GRANT ALL privileges ON school.* TO 'SchoolAppUser'@'localhost';

Part – 17 (Django Admin UI)


We have admin URL link in urls.py file. Django will create an admin page and
userthis user has all permissions.
Now access that URL : http://127.0.0.1:8000/admin/
Note : We need username and password , in order to create a user need to follow
below steps:
• python manage.py createsuperuser
By using above credentials, we can login like below.

Note : To show our models we need to register that model into admin like below.
Now see admin page :

Note : Below we can see only names for student but we need more data to be
show when we open a student model.
To get that we need to declare one model class at admin page like below:

Output in admin page :


Part – 18 (Django ORM Part-1)
Concepts :
1. Select all records from table (all)
2. Select only one record from table (get)
3. Select particular columns from table (values_list, values and only)
4. Select multiple records from table(filter)

1. Select all records from table.

SQL> Select * from table;


ORM> Model_Name.objects.all()
• Note : When we are using ORM commands result will provide in query
set format.

2. Select only one record from table

SQL> Select * from Student where id=3;


ORM> Student.objects.get(id=3)

Note :
o If result not matched then provide error like “DoesNotExist: Student
matching query does not exist.”
o We can also use filter instead of get. Here get provide only on record
where filter provide multiple records with provided condition.
o And also, we can use only “=” equal operation in get but we can use
other operations like “>” greater then ,”<” less then etc. in filter.
o In Get we will get only one record in filter we will receive query set.

If try to get multiple records from get method:

Here we have 2 records with father name as “Somesh” like below:

Try get now in ORM:


Note : So, we need to apply get only on primary key or unique constraint columns
only. For other better to use filter.

Let’s see by using filter method :

3. Select particular columns from table

Note : we need only id, student name and contact from Student table.

SQL> Select id,name,contact from Student;


ORM> Student.objects.all().values_list('id','name','contact')
Student.objects.all().values('id','name','contact')
Student.objects.all().only('id','name','contact')
Note : in only method will provide id even you select or not like below:

Difference between values_list , values and only :


values_list : Provide list of tuples of each record in table with mentioned columns.
values : provide list of dictionaries of each record in table with mentioned columns.
only : It provide query set of each record with mentioned columns (default id will
provide)

4. Select multiple records from table :

Comparison Operators :

SQL>select * from Student where id>3;


ORM>Student.objects.filter(id__gt = 3)
Like Operation :

SQL> select * from Student where name like '%h%';


ORM> Student.objects.filter(name contains='h')
IN Operation :

SQL > select * from Student where id in (1,3,4);


ORM> Student.objects.filter(id in=[1,3,4])

Logical Operations:
AND :

SQL > select * from Student where id>3 and st_class='NURSARY';


ORM> Student.objects.filter(id gt=3) & Student.objects.filter(st_class='NURSARY')
OR:

SQL > select * from Student where id>3 and st_class='NURSARY';


ORM> Student.objects.filter(id gt=3) | Student.objects.filter(st_class='NURSARY')

NOT :

SQL > select * from Student where NOT id>3;


ORM>

Operations table :
Symbol Description Example
gt greater than SQL>Student.objects.filter(id gt=3)

ORM>Select * from Student where id>3;


gte greater than or SQL>Student.objects.filter(id gte=3)
equal to
ORM>Select * from Student where id>=3;
lt less than SQL>Student.objects.filter(id lt=3)

ORM>Select * from Student where id<3;


lte less than or equal SQL>Student.objects.filter(id lte=3)
to
ORM>Select * from Student where id<=3;
contains Like operation SQL> select * from Student where name like '%h%';
(case sensitive)
ORM> Student.objects.filter(name contains='h')
icontains Like operation SQL> select * from Student where name like '%h%';
(case in sensitive)
ORM> Student.objects.filter(name icontains='h')
startswith Starting condition SQL> select * from Student where name like 'h%';

ORM> Student.objects.filter(name startswith='h')


endswith Ending condition SQL> select * from Student where name like '%h';

ORM> Student.objects.filter(name endswith='h')


in In operation SQL > select * from Student where id in (1,3,4);

ORM> Student.objects.filter(id in=[1,3,4])


& AND Operation SQL> select * from Student where id>3 and
st_class=’NURSARY’;

ORM>Student.objects.filter(id_gt=3) &
Student.objects.filter(st_name=’ NURSARY’);
|(pipe) OR Operation SQL> select * from Student where id>3 or
st_class=’NURSARY’;

ORM>Student.objects.filter(id_gt=3) |
Student.objects.filter(st_name=’ NURSARY’);
exclude NOT Operation SQL> select * from Student where NOT id>3;

ORM> Student.objects.exclude(id__gt=3)

Part – 19 (Django ORM Part-2)


5. Aggregate functions (avg, sum, max, min, count):

To work with aggregate functions, we need to install aggregate functions like


below:
From Django.db.model import Avg,Sum,Min,Max,Count
Student.objects.all().aggregate(Avg(‘contact’))
Aggregate function with filter :

6. Insert records into table (create):


Other method to insert data :

Student.objects.create(name='sowmya',father_name='jagadeesh',st_class='LKG',co
ntact=8888888)

7. Bulk Insert records into table (bulk create):

Student.objects.bulk_create(
[Student(name='s1',father_name='f1',st_class='c1',contact=111111),
Student(name='s2',father_name='f2',st_class='c2',contact=222222),
Student(name='s3',father_name='f3',st_class='c3',contact=33333333)])
8. Removing record(Delete):

Single record deletions :

student = Student.objects.get(id=11)
student.delete()

Multiple records deletion :

students = Student.objects.filter(id in=[9,10])


student.delete()

9. Updating record(update):
10. Sorting of records:

We use order_by method to sort the record.

Ascending order :

Student.objects.all().order_by("name")
Descending order:

Student.objects.all().order_by("-name")
Important note in sorting :

In above we can father name of Pooja and manasa was same so in first we got that
records based on id.
Where in second when we provided two options in sorting, we got manasa came
first after pooja is came.
Reason is in second query we are saying that if we found any same records in first
order by then use second condition for further order.

Refer this for more details :


https://docs.djangoproject.com/en/4.1/ref/models/querysets/

Part - 20 (Model Forms in Django)

In this tutorial let’s see how to get forms from our model. This can be done by
using Model Forms concept.
Steps :
1. Create forms.py file at app level directory.
2. Create a class in forms.py file which inheritance form Model Forms
3. Create Meta class inside your above classes
4. Use model form in views and send it to respective templates.
5. Output

Implementation:
1. Create forms.py file at app level directory.

2. Create a class in forms.py file which inheritance form Model Forms

3.Create Meta class inside your above classes


4. Use model form in views and send it to respective templates
5. Output :
Note : we can also pass this for as table and unorder list also like below :

As Table :
As Unorder List :
Part – 21 (Saving form data into database)
Views.py:

Template :
Output :

We are able add data now.

Part – 22 (How to create HTML forms using Django forms)


Note : Somet imes we need a form without models that time we use forms
concept in Django.
Like we need user input without saving the data into database. That time this
concept is useful.
Let’s see how to create a html form with Django :

Steps :
1. Create forms.py file in application folder.
2. Create a class which inheritance from form.Form.
3. Define fields in that form class.
4. Use this form class in views
5. Using this form object in templates
6. Output

Defining form class in forms.py :

Write logic in views.py file :


Show that form in templet :

Before this create a URL in urls.py file to access this :

Output :
Note : We will get output to console as we have printed in views.py file

Main use of forms concept is to create a html form without writing a html code
Part – 23 (CRUD Operations with function-based views)
CURD -- > Create Update Read and Delete

We have already seen create and read.

Delete operation :
Steps :

1. Create a URL that must take id as input.


2. Create view that must take a id as input
3. Need to get that id record from database and delete.
4. Now we need to call that URL with id when user clicked that particular
delete link.

URL :

Views.py :
Template :

Output :

Before delete :
After delete :

Update Operation :

Steps :
1. Create a URL that must take an id as input.
2. Create a view this also must take an id as input.
3. By using that id need to create a form.
4. Use that form in template.
5. Output
URL :

Views.py :

Note : if user come with get method, then showing existing data with form. After
he updated that request is come as post . if request come as post then we are
saving data with existed data to database.

Template :
Output :
Before update data for rakesh :
After update data for rakesh :

Part – 24 (Class Based Views)


We have worked on function-based views previously but by using class-based
views we can reduce our code little bit.

Steps :

• Import view (from django.views.generic import View)


• Create a subclass or inherit from View
• Declare separate methods or functions for each HTTP methods
• In urls.py while creating URL give view name as view name.as_view().

Practical implementation :
Views.py :

Urls.py

Output :
Part – 25 (CRUD Operations using Class based views)
Class-Based views will do our work very simple ; we just need to declare don’t need
to do anything like function views.

Other views in generic:


1. View
2. ListView

Creating new model to work with class-based views:

1. Reading all records from database using class-based


views (ListView) :
Note : we need to use ListView to read the all records from database.
My Explanations :

• Model Name_list is default query set result in class-based view.


• If we want to change then need to assign a value to variable of
“context_object_name”.
• Model Name_list.html is default template name which look Django.
• If we want to change template then need to mention value to variable of
“template_name”

Practical implementation :
Urls.py :
Views.py :

Create teacher_list.html page :


Output :
Example with custom template name and context name:

Views.py:

Html:

Output:
2. Reading only one record from database (DetailedView) :

Default query set → model name


Default HTML page → Model Name_details.html
Practical :
Views.py :

Urls.py :

Teacher_details.html :
Output :

Note : Instead of enter total URL by user let add a URL to teacher list page . when
user can click that record and see details.
Output :

When user clicked on 1 then below page will come.


3. Create new record into database (CreateView) :

Default queryset → form


Default template → model name_form.html
Views.py :

Urls.py :

Teacher_form.html :
Output :

If we try to add teacher we got below error.


Note : when user clicked on “add teacher” then record will be create in table but
we need give return page for this.

For this we need to create a method in our model.


Models.py :
Note : Based on our URL we need to declare kwargs in reverse method.
This “ListTeachers” is name of URL that we need to declare when we are creating a
URL like below.

Output :

Now able to add new teacher easily.

4. Update a record in database (UpdateView) :


Note : Update is very easy after declare of create in class-based views.
Views.py :
Urls.py:

Teacher_form.html is also use full for update page.

Output:

Records before update:

Updating record :
After update :

Note :we can see that after data updated it redirecting to list of teachers as we
mentioned in models. But if need any other redirect the follow below:
Views.py :
By using success_url we can change our redirect after success full operation.

5. Delete a record in database (DeleteView) :


Views.py:

Urls.py:

Template:
Output:

If I try to delete any record I facing below error.


Note : Django by default need a model name_confirm_delete.html page to delete
any record.

So, let’s create that:


Output:

When I am clicking on confirm below error it giving.


Need to provide success_url in views like below:

Output :

Now everything working as expected.


Part – 26 (Authentication in Django)
In this we are going to learn security in Django by using two ways called
authentication and authorization.

Authentication is the process of verifying who a user is, while authorization is the
process of verifying what they have access to.

Authentication and authorization :


Authentication means who need to access our application (verified by using login
form).
Only authenticated user can access that particular website.
After login into application authorization take care of which links or feature that
user can access or not access.

Authentication :
User need to login to application to access any services in that web page this can
be set by using authentication.

Steps :
1. Add the auth URLs
2. Create a login form
3. Secure the views
4. Create Users
5. Testing
6. Class-Based secure views
7. Logout
1. Add the auth URLs :

Note : Just we need to include this URL in our main project.

2.Create a login form


Create a registration folder in template folder then create login.html file.
Note : we will have User model default in our project . from that model we will get
form for this login.html file.
3.Secure the views

Note : we need to add views where user login required. This will work only for
function-based views.

4.Create Users
We have already created admin user but now we need to create a normal user.
Note : we have created test1 user successfully.

5.Testing :
Try to login first without authentication:

Able to see below home page after login(authenticated):

Let’s try to connect class-based views without authentication:


Note : able to access class -based views as we have not provided login required.

6.Class-Bassed secure views :


For class-based views we need to pass login required at URL level like below:

Testing :
Note : asking login for class-based also.

7.Logout :
We can use this URL http://127.0.0.1:8000/accounts/logout/ to logout from
current user.

Note : after logout we are coming this page but we need our custom page. So
follow below steps.

Add LOGOUT_REDIRECT_URL in settings.py file.


Note : we can use any URL after logout user.

Testing :
Note : When user clicked on logout it taking to login form.
Note : add below two setting for good redirect :

Part – 27 (Authorization in Django)


Authorization means permissions to our users based on requirements.
We use permission_require decorator to give permission to user.

from django.contrib.auth.decorators import permission_required


@permission_required('app name.Operation name_model name')

Types operation names :


1. Create →add
2. Read →view
3. Update →change
4. Delete →delete

We are asking permission for delete a student in our school app.


Note : Like this we can give which activity we need to secure.
Testing :

Let’s login to website and open list of student:

Now let’s try to delete Ramesh record.

Note : Whenever I am trying to delete then it taking me to login page like above.
Instead of this we can also provide a raise_exception=True to our
permission_reuired decorator. Then it gives error like below.

Output :

How to give permissions to that particular user:


Admin page → users → select user → User permissions
Note : Now this user able to delete student as we provided permissions.

Groups concept in admin:


For example, we have number of teachers in school . for all teachers will have
same permissions so that time we will make all teaches in one group and provide
access. Like wise we will use groups.
Part – 28 (Session Management in
Django)
Explanation :

• As we discussed in web application, we have client and server environment.


• As we already know that in client-server environment client will send a
request to server and server will give a response to client.
• In order to maintain a commutation between client and server we required
a standards or protocol. Mostly we use a protocol called HTTP(Hyper Text
Transfer Protocol)
• When ever we are working with HTTP protocols that time, we need to talk
about Session management.
• Usually, this HTTP is called a stateless protocol
What mean by stateless protocol...?

• Stateless protocol mean our HTTP will not store any data. When one request
come previous requested data will be loss. Here data means state.
• So, we use these 3 methods (Hidden Variables , Cookies and Sessions) to save
important data or state.
• So, HTTP is stateless so we use above methods to make as a Stateful
application.

Concept :

As we know that we will host our application in one server or multiple servers.
When a user search that URL in his local machine browser then that browser will
connect application and get done his work.
Here user no need to download any files related to application to use application
he just needs a laptop with internet to access that particular application.
Here we can see that client will connect application through browser and done his
work. For example, Facebook application many users will use that application for
different purpose.

As we know that if two people want to communicate each other then there should
be a one language like to communicate client and server we are using HTTP.

One of the use of these sessions:

In below screen we can see that your browsed history. Here amazon web site is
not storing this information into their databases until we place a order. Then how
this data is coming mean by using cookies or sessions.
Then where these data are storing...?

This data is storing in our own browser only.


When we are doing any activity that need to store that time cookie will create at
client side.
Cookies : Cookie is nothing but a small amount of information i.e is stored in
client side(browser) by server that can retrieve at a later time.

Note : these most of times used for recommendation.

Demo with Firefox browser how cookies will store:


To see cookies in Firefox, follow below steps:
See cookies before browse anything:
Now visiting amazon website and seeing some products:
Practical implementation:
Hidden variables:

In this we will create a hidden variables those variables will move between client
and server every time a request and respond in happening. If we need to change
the values of hidden variables we will change and send with request or response.
Drawback of hidden variables is , if we have 100 variables then every time we need
to send that hidden variable so there might be change of getting slow response or
request or any other network error.

Here we have below add admission form is there in our school project. when ever
a user enter his/him details then I need to show admission name in all other places
. this we can achieve by using hidden variables.

To achieve this we need to store provided details into a variables like below :
Here we are storing the given details and sending these into home page first.
Index.html:

Output:
Now we have data in our own variables, so now we need to create a hidden
variables and use where ever we want in our project.

Working with hidden variables:


Every anchor tag we will convert into form and pass these variables using hidden
input type.

Let’s do practically send those 4 variables to add admission page like below:
Indesx.html :
We are sending date to view in hidden variable format like above.So we need grab
these hidden variables and send it to where you want like below.
Views.py :

addAdmission.html:

Output:
This way we can send hidden variables from one page to other page. But using
hidden variables is very hard.

Drawbacks :

• Hard to implement and manage hidden variable for developer.


• Using hidden variable make some delay in network side also.

Cookies :
Working with cookies , need to know below topics:
1. How to create a cookie
2. How to retrieve a cookie
Create Cookie:

response.set_cookie(name,value,expiry_name)

Retrieve cookie :

request.COOKIES → To get all your application related cookies


request.COOKIES[name] → To get specific cookie

Cookies practically :
When ever use click on add admission this will send to response :

Instead of sending response directly lets create a variable and store there like
below:
Note : before we are sending response just creating a cookie then sending
response.

Output:
Cookies before add admission :

Below the path to see our website cookies:


Inspect→storge
Cookies after added admission:

Note : Now these variables are available all over application. We can use like
below :
addAdmission.html:
Output :

Note : Cookies are differ for differ browsers :

Chrome:
Firefox :
Drawback of cookies :
Some people will disable the cookies.
Let’s try by disable the cookies in our system.
Now lets try to open our website :

Note : reason is our Django will store crsf token as cookie.


Here our Django is using crsf token also cookie but by using some other technology
to develop web application when if cookies is disabled it wont work. That time we
can use sessions instead of cookies.
Sessions :
In sessions concept values store in both client and server side as well.
Advantage of using sessions is when data is not available(not available means
cookies is disabled) at client side then data will fetch from server side.
A session is nothing but a series of actions that performed by a user on a website.
Example : one user logged into our website and performed some actions then log
outed from website this is called one session.

Workflow of sessions :
Sessions are same like cookies but only one difference is data is available at both
client and server side. when ever client turn off cookies the server will rewrite each
URLS. Rewrite means it will add necessary data to the URL and send it to client.

Create sessions :

request.session[name]=value
Retrieve sessions :

request.session.get(name)

Practical implementations :
Output :

Note : Sessions are also work same as cookies but only one difference is sessions
will store data in both client and server side. If data is not available at client by
using rewriting it will get data from server.

============================= The End ===========================

You might also like