Django
Django
Django
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:
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.
• Within project, you have multiple app’s which is used for particular task.
• Collection of apps or single app is called Django 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:
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 :
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.
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/
•
2. Adding templates in settings.py file :
3. Creating templates/html in template folder :
Note: Now we are getting data from templates not from HTTP Response. So,
create templets for finance app also and test those.
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:
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.
Views.py :
Urls.py:
Templates:
Sample1.html
Sample2.html
Sample3.html
Outputs:
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.
{% extends "base.html" %}
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.
View :
URL :
Template :
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.
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.
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 :
3. Update table
4. Delete table
After creating model, we need to register those models in admin.py file to get
show in admin page.
Steps :
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:
MySQL settings:
Note : if we are running local host then it no required to “Host” and “Port”.
To drop user:
DROP USER 'SchoolAppUser'@'localhost';
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:
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.
Note : we need only id, student name and contact from Student table.
Comparison Operators :
Logical Operations:
AND :
NOT :
Operations table :
Symbol Description Example
gt greater than SQL>Student.objects.filter(id gt=3)
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)
Student.objects.create(name='sowmya',father_name='jagadeesh',st_class='LKG',co
ntact=8888888)
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):
student = Student.objects.get(id=11)
student.delete()
9. Updating record(update):
10. Sorting of records:
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.
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.
As Table :
As Unorder List :
Part – 21 (Saving form data into database)
Views.py:
Template :
Output :
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
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
Delete operation :
Steps :
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 :
Steps :
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.
Practical implementation :
Urls.py :
Views.py :
Views.py:
Html:
Output:
2. Reading only one record from database (DetailedView) :
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 :
Urls.py :
Teacher_form.html :
Output :
Output :
Output:
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.
Urls.py:
Template:
Output:
Output :
Authentication is the process of verifying who a user is, while authorization is the
process of verifying what they have access to.
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 : 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:
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.
Testing :
Note : When user clicked on logout it taking to login form.
Note : add below two setting for good redirect :
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 :
• 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.
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...?
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.
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 :
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 :
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 :
Note : Now these variables are available all over application. We can use like
below :
addAdmission.html:
Output :
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 :
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.