Django Notes

You might also like

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 40

Django Notes

 Django Session 1
 Django
a. We can use Django to develop Web Application.
b. Example of Web Application: Gmail, Facebook
c. Any application which we can access over the app are called Web application
d. For any web application, 2 things must be required (i) Front End (ii) Back End
e. What is Front End: On a website, whatever is there on the screen is front end.
f. Back End: The response (of front end) generated by which code or which technology or who decided
this is the response should be displayed to the user is called as the back end. That code or that
technology is considered as the back end technology.
g. We can display the front end content by using html, CSS, Java script, Bootstrap (These are front end
technologies)
h. Whatever you are seeing, How you can you display the content on the screen in a beautiful way is
done by using these front end technologies (html, CSS, java script (JS), Bootstrap, Bootstarp,
jQuery,DOM)
i. Who decides these things should be displayed to end user: Back End Technologies or Back end Code.
j. In the Back end who decides this code should be displayed to end user: That Person is back end
k. For back end which technology we use: Python.
l. In the back end we use Python as the Programming language, Django as the framework, some data
base.
m. Database we may use be sql, mysql, or sql server
n. Django is also back end technology.
o. Front End Technologies are used to display the content on the front end.
p. Jumbotron is bootstrap technology component.
q. Anchor tag – html content
r. By using which technologies we displayed the content on console or to the end user is called front
end technologies.
s. To develop the front end which technologies we are going to use, these technologies are called as
Front end technologies.
t. Every web application contains 2 components: (i) Front End (ii) Back End
u. Front end is what we are seeing. How we can develop the front end is called as front end
technologies like JS (Java Script)
v. What you are seeing is decided by back end.
w. The back end code (python Code) is responsible for to generate or to decide the front end code.
x. In back end we are using the Python code.
y. Django is the back end web application development framework.
z. By using Python, by using Django, by using database (back end technologies), we can decide what
things should be displayed to the end user.
aa. How these things should be displayed to end user is decided by Front end Technologies (html, CSS,
Java script (JS), Bootstrap, iQuery, DOM).
bb. If you know both back end and front end then we can develop beautiful application but as the part of
this course, we will discuss only back end technologies
 Django
a. Django is the back end web development framework.
b. Advantage of Django: Django is freeware. To use Django, we are not required to pay single money.
c. Django is the open source framework.
d. Advantage of open source is that if it does not fulfill your requirement then you can customize it
according to your need.
e. Django framework is completely written by Python Programming language.
f. Django is maintained by DSF (Django Software Foundation). DSF is Non profit Organization. DSF is non
commercial.
g. djangoproject.com is the official website.
h. Django is based on
i. MVC (Model View Controller) is the most popular framework or design pattern to develop web
application. (Almost all application is going to be developed by MVC but not Django)
j. The biggest specialty of Django is that Django follows/based on the MVT (Model View Template)
design pattern instead of MVC.
k. M - Model, V-View, T-Template are the most important words to be used many times.
l. Understanding above 3 words is nothing but your Django course.
m. Famous Web application designed by using Django: Spotify, Disqus, Instagram, Spotify, You tube,
drop box, Washington post,quora etc.
n. Django was created in 2003 as an internal project at Lowrence Journal world news paper for their
web development.
o. Django is preferred as the most clear documentation is present in Django only.
p. The Original version of Django was developed/created by Adrian Holovaty, Simon Willison.
q. Django was released to public for the first time in July, 2005.
r. Why the word Django: Django Reinhardt was the guitarist.
s. 95% things are done by Django itself. 95% things are automated.
 Django
a. Why we require to choose Django:
b. Top 5 features of Django framework:
c. Limitation of Django: Django can be used only for web development. (But Spring framework can do
spring transaction, enterprise application). SO Spring MVC is Django.
d. Top 5 features of Django Framework:
e. (i) Fast – Django is very fast. (Only 5% we have to do, rest 95% work is done by Django itself).
f. (ii) Fully Loaded: For every web application there are some commonly required things like
authentication, security etc. for These type of activities already predefined application are available
inside Django. Like for Authentication application is already available in Django and we don’t have to
write code for that. We have to write only 2 line code. For many activity, there are predefined code.
g. (iii) Security: Django itself take care of security things like SQL injection attack. CSRF – Cross Site
Request Forgery, cross site, click jerking etc. Django has already inbuilt solution for these problems.
We just have to mention {%csrf_token%} to ensure the above activity.
h. (iv) Scalability: Django application is scalable for any number of request. (Like Django is prepared for
increased number of request) i.e. can handle heavy traffic
i. (v) Versatile: Different areas, different domains. You can develop any school project by Django and
even a NASA project can be developed by Djanga. So Versatile means Django can develop a ranage of
application i.e. from smaller to bigger. i.e. can be used everywhere.
 Session 2
 Django is open source, freeware, web development framework for Python.
 Django can do up to 95% repeated work.
 Fully Loaded: Django has several already inbuilt application.
 Security: Cross site Forgery is taken care by Django itself.
 Scalability: High Traffic is managed by Django itself. Application developed by Django is scalable.
 Versatile: Diversity: Everywhere we can use Django.
 Django is specially designed web development framework.
 How to install Django
 Atom IDE: Atom is one IDE. You can even use Pycharm which is also an IDE.
 IDE (Integrated Development Environment): (Internet informations)
a. IDE is a software for building applications that combines common developer tools into a single
graphical user interface (GUI)
b. An IDE typically consists of:
c. (i) Source Code Editor
d. (ii) Local Build Automation
e. (iii) Debugger
 Django
a. Django contains several applications + Configuration information
b. Configuration information: Information like URL pattern or database are to be configured inside the
project. There is some file available for it.
c. If you want to develop application by using Django, first we require to create project.
d. Without existing project, there is no chance of existing application .
e. Every Django should be a part of the project. SO if you want to create a application, first we require to
create a project.
f. Same application can be used in multiple projects.
g. Django apps are reusable. Suppose we developed registration application then we can use this
application in any project.
h. So while developing application, consider the reusability.
i. Django application is expected to do certain pre defined activity. A group of such applications and
configuration information is considered as the project.
j. Project can contain several application.
 How to create Django Project
a. If you have installed Django application in your laptop then you can create any Django application.
b. Django-admin startproject firstproject: Django-admin is the tool: we use this command to start this
project (project name is firstproject).
c. I think we have created djangoprojects folder inside c drive so since our cmd is pointing towards this
djangoprojects folder and we are running the command Django-admin startproject firstproject so the
first project folder will be created inside atom the whole thing will be created inside djangoprojects I
think
d. We have created a djangoproject folder inside c drive and we have connected that folder inside Atom
IDE by using Addfolder by going inside File. SO that’s why djangoproject folder is showing inside atom
IDE.
e. Also ensure that commandprompt also points towards this Djangoproject folder.
f. When we install Django, automatically you will get the Django-admin toll .
g. Django-admin tool is the command line utility.
h. Before running of the command Django-admin startproject firstproject, there will be nothing inside
the atom folder djangoproject but as soon as we execute the Django-admin startproject firstproject
command the firstproject folder will be created inside the atom ide.
i. As soon as we execute the command Django-admin startproject firstproject , your basic project is
already ready.
j. Before running of this command (Django-admin), the djangoprojects folder in atom is empty.
k. As soon as we run this command, our basic project is ready and till now djangoprojects folder was
empty in atom but a new folder firstproject will be created inside the djangoprojects folder in the
atom ide.
l. The aim of this Django-admin startproject firstproject command is to create project folder i.e.
firstproject
m. Inside the firstproject, one more firstproject will be created. Many files will be created by manage.py
is the most important file.
n. Mange.py is the most common used script.
o. My View: What I think that whenever we use any command then there is no need of writing cd in
cmd but if we want to enter in particular location like particular folder then we have to write cd and
then the desired path where we have to enter.
p. File names generated inside firstproject (which is already under firstproject folder): __init__.py,
settings.py, urls.py, wsgi.py file (These files will be created inside inner firstproject folder)
q. Now inside outer firstproject folder manage.py file will be created.
r. This is python package.
 Description of File
a. __init__.py: This file will tell that firstproject is the python package. (remember __init__.py is a file
genered inside inner firstproject folder). Role of __init__.py file is to indicate that firstproject is a
python package.
b. All project related settings are defined under settings.py file. These setting information conatin which
database we are using, which template we are using
c. Urls.py: contains all our urls. We have login page. So if we want to access login page so which urls will
be used to access login page. So these things are contained/defined under urls.py file. These urls are
also called url pattern. What are various urls ffor our application is contained by urls.py
d. Wsgi.py (Web server gateway interface): This is special file but generally we do not use this file. This
file is used when we move our project to the production or live environment.
 Mange.py
a. To manage the projects, to run the project, to run sever, to make migration
b. Other important files are: settings.py and urls.py
c. These files are Django specific terminology.
 Django
a. If you want to create a webapplication by Django then a project must be already ready.
b. __init__.py is dummy file, it does not contain anything and the oonly role of __init__.py is to tell that
firstproject is a python package.
c. Rank 1 – manage.py, rank2,rank3 – seetings.py, urls.py, others are just dummy file
d. Name of the project – firstproject
e. This firstproject can contain any number of application (any project can have multiple application)
f. This project contains some application internally (As Django provides a vide range of inbuilt
application like suth, session, admin application)
g. How to confirm these applications are present. –
h. Go to seetings.py – open it – see installed apps – here you will see many applications are installed and
Django already provided these inbuilt applications.
i. Though we have not created any application till yet but Django has provided inbuilt applications like
admin, contenttypes, messages, staticfiles etc.
 Run the Serve and send the request
a. Request you are sending for default applications
b. What is Server (Web Server): A project may have several application. Now we want to run our
application. To run our application who is responsible to provide the environment ? Server (Web
Server) is the responsible to provide the Environment.
c. So when we are send ing the request to application, first the request will come to server only, server
will identify the corresponding application, Now the server is going to forward the request to
corresponding application and the response is going to send to the end user.
d. Main job of web server (server) is to provide the environment to run the application. Without
environment, application cannot run so our application will not be able to send the response to the
end user.
e. The Application provided response the server is going to handover to client and that’s why client
server architecture.
f.

g.
h. What I think: We send the request to server, server sends it to the application, then application
performs the job and after performing the job application send the response to server and then the
server sends this response to the end user.
i. So if you want to run your application, if you want to send the request then compulsory you must run
the server.
j. How I can run the server: Django provide inbuilt server (we are not required any external server).
k. How we can start the server: When we created the project manage.py was created. Manage.py is
used to run the server.
l. Use the following command to run the server:
m. py manage.py runserver
n. python manage.py runserver (sometime py command does not work so use python then)
o. We have to run manage.py script to run the server but manage.py is available inside outer firstproject
folder so:
p. Step1: Go to that outer firstproject foldr: Use cd firstproject (Extra Thing: if you use command tree /F
then you will get what is inside the firstproject folder)
q. Step2: Now run the command: python manage.py runserver (server will sun for the first time)
r. Currently we need not to worry about Migration.
s. Meaning of the line - http://127.0.0.1:8000/ which came in the description when we ran the server.
t. Meaning of the line:
u. http: is a protocol
v. 127.0.0.1: It is the host. This indicate on which machine your Django server is running. 127.0.0.1 is the
local host. In this local host multiple services application is running like notepad, world, movies,
goggle chrome etc. Now where is the Django running ?
w. 8000/ - Django server is running on 8000 port number. 8000 is default port number for Django server.
x. Now send the request (as server is already running). Paste this http://127.0.0.1:8000/ on chrome. You
will get djnago welcome page. (what I think is that our request is sent by server to chrome application
and as a response to that chrome functioned, though the response was sent back to us by server
only)
y. Will http://localhost:8000/ will work ? Answer: Yes it wil work for sure.
z. 8000 is the default port number where our server is running, suppose I don’t like this number. So is it
possible to change the port number. Yes it is possible How: Command to use the run server p
manage.py runserver, just pass the port number just after this command to run the server on desired
port number. So the full command will be:
aa. Py manage.py runserver 8888 (If you want to run the server on the 8888 port)
bb. Now to do to this first stop the server (As the server is already running):
cc. Stop the server by ctrl c.
dd. So now run the command Py manage.py runserver 8888 now onwards your server will run on 8888
server. (Use higher number for port number as first 256 ports are reserved for system)
ee. Don’t use customized port number like 8888, always use default port number i.e. 8000.
ff. Now send the request again with new port number: It will work
gg. This is the method how you can set your own port number (but only recommended port is default
port i.e. 8000)
 Firstproject folder
a. Is there any diffrenec in folder after running the server.
b. Answer: Yes, db.sqlite3 file was created.
c. So Django provides and inbuilt data base (DB) sqlite3. This is the default dayabase provided by
Django.
d. So we are not required to install external database. For small to medium application this default db
sqlite3 is more than enough. No requirement of using sql, oracle etc.
 So Django provides one inbuilt server and Django also provide one inbuilt Data Base(DB sqlite3).
 We can configure our own development server like Apache tomcat etc.
 We can also configure our own DB like Oracle, SQL
 8000 is the default port number where server is running.
 Application
a. To start the application use:
b. Py manage.py startapp testapp
c. Startapp is the command to start the app but testapp is the name of the application which we want
to develop. (we can take any name in place of testapp)
d. So manage.py also helps in starting an application.
e. Observe that before running the above coomnad, inner firstproject folder things like 5 files and
sqlite3 database.
f. Now stop the server.
g. Now we want to start the application:
h. Since we are inside firstproject folder as there only manage.py is available so ensure that cmd points
towards the firstproject and then use the command of startapp.
i. The full command on cmd after stopping the server (ctrl c) is:
j. C:\Users\digvijay\djangoprojects\firstproject>py manage.py startapp testapp
k. Now application is ready.
l. For your testapp whatever the default files are required, Django will provide all of them
m. Now obsere that after running the above command, a folder with the appname (tesapp) got created
which contains multiple files. These multiple files inside testapp was created by Django.
n. The created files are:
o. __init__.py
p. View.py
q. Models.py
r. Admin.py etc.
s. Apps.py
t. One folder migration also got created which contains empty file __init__.
u. Today (in the beginning) one file is very important – vies.py
v. If you want to start the python, views.py file is the most important. Other files will come slowly
(Django itself created these files after we ran the command).
w. Total 6 files got created inside testapp. Though I file inside migration folder.
 Commands used till now
a. Django-admin startproject firstproject
b. Py manage.py startapp testapp
c. Py manage.py runserver
 Session 4
 Inside inner firstproject folder 4 files are present: These are: (i)__init__.py (ii) settings.py (iii) urls.py (iv)
wsgi.py
 Wehenever we create application then testapp folder get created. 6 files get created which are: (i)
__init__.py 2. Views.py, models.py, admin.py,apps.py,tests.py
 Very Important files: view.py, settings.py, urls.py
 Sqlite3: inbuilt database provided by Django
 Django also provide development server.
 When we created application, one folder also get created, the name of folderis migration folder. This
migration folder is very important for data base (db)
 For our application etc. we require manage.py files but manage.py file is inside firstproject folder so our
cmd should point towards the firstproject folder then only we can access the manage.py file and hence
the commands inside the manage.py file. (For every project you have to do this)
 Cd means change directory. So cd means can you please eneter into this directory means the folder
written after cd.
 Application
a. Whenever we are sending the http request to server, Server will send the request to application. In
the application who is responsible to provide the required functionality ? That component is called
View Component. View meant for Business Logic. So View is the responsible to provide the response
to our sent request.
b. That’s why View is a function. It is always going to take http request as input and it will always provide
http response as the output.
c. View is a function which we will define inside our Django application .
d. That’s why in our folder there is views.py file.
e. View contains all the business logic, which response you have to provide, all those code is written
inside view.
f. There are 2 types of views: (i) Function based views (ii) Class based views
g. Currently we will talk about function based views then later class based views.
 Function based views
a. Where you have to define views ? Ans: Inside views.py file.
b. Things written inside view.py file.
c. The logic is:
d. Hello_world_view() is the function.
e. This function will always take request as the argument i.e take request as the input.
f. So Argument is the input so request is the input.
g. Now it has to return response. Return http resonse.
h. Here http response contain html code so for simplicit write <h> hello this is the response from
Django.
i. Observe carefully:
j. Hello_world_view(requet) is a function but HttpResponse() is not a function, this …
k. HttpResponse is a Class which is available inside django.http module. So compulsory you have to
perform import statement. So
l. So write: from django.http import HttpResponse
m. Interview Question: How to write View Functio: Can we take any name in place of request. You can
take any name, request is just a variable. (But recommended to use request to improve readability)
n. You cannot take any name in place of HttpResponse as it is a class name.
o. Now application is ready and view function is also ready. Now end user is responsible to send the
request. End user is responsible to send the request for view function and he has to get the response.
p. You have defined something but you have to convey end user that you can call this view function with
this name. We have to specify this information to end user
q. How to do this: Configure URL pattern for our end user.
r. Once you configure URL pattern for our view, by using that URL pattern, end user can call our view,
happily he will get his required response.
s. So where we have to define URL pattern for our view. Answer is: inside urls.py
t. Inside this file we have to write the url pattern.
u. This file is available at project level. (Remember these things) (Other level is application level)
v. We defined view function inside views.py. views.py is available inside testapp folder. urls.py is
available inside firstproject. So whatever content is available inside views.py file (inside testapp), we
have to access this content inside urls.py file (inside firstproject). (My point is that through urls user is
accessing the view that’s why views data have to be accessed inside urls file) That’s why compulsory
import statement must be required. So
w. So go to url file and write: from testapp import views (This means we have to make sure that views
module is available to urls)
x. The screenshot is:

y.
z. In every application from testapp import views activity is compulsory. Now Views content will be
available inside url.
aa. Now go inside url file. Now inside urlpatterns we have to define our own url pattern.
bb. For admin, already url pattern is available. Copy that in next line. Now by whatever name you want
end user should call the view, put that desired name at the place of admin. So we convey to end user
that call our view with this url pattern. So write hello in place of admin. This is our hello url pattern.
cc. Now this hello url pattern is matched with which views ? this hello url pattern is matched with
views.hello_world_view which is to be written in next column.
dd. The screenshot is:

ee.
ff. If the end user is sending the request with hello url pattern then this view.hello_world_view is going
to execute and will provide required response. (Remember that HttpResponse class is inside the
hello_world_view function only)
gg. How end user will send the request: http://127.0.0.1:8000/hello. If user send this
http://127.0.0.1:8000/hello then the control will go to hello_world_view function and now this
function is responsile to provide http response which will be displayed to end user.
 Adding Application to the project
a. We have to add this application to the project in settings.py file.
b. So that Django can recognize our application.
c. Settings.py is at the project level.
d. Open settings.py
e. Observe installed Apps line: this tells which application are installed in this project. So obviously we
also have to add our application in this project.
f. Name of the application testapp. So just write ‘testapp’ inside installed apps and save it by ctrl s.
g. The screenshot is:

h.
 Full Flow of the process
a.

b.
 Hugely Important Things which are different from Sir’s Project
a. In urls.py file, you have to use name path instead of url. The screenshot is:
b.

c.
d. Save all the things by pressing save button inside file.
 Full process created by me:
a.

b.
c. inside settings.py file
d.
e. Inside views.py

f.
g. In views.py file:

h.
i. The output when send on browser this: http://127.0.0.1:8000/hello
j.

k.
 Some Points
a. When end user sen the request, the request goes to server.
b. Then server first opens the urls.py file.
c. Now the ‘end user sent’ url pattern is mapped to which view functions. (In current case
hello_world_view)
d. Now server identifies this and request will be forwarded to this view function
e. Now view function is responsible to provide the response.
f. The flow is:

g.
 Developa another application
a. Develop application for ‘the current server time is’

b.
c. Here datetime package contains datetime module. This datetime module contains now function. now
function will provide current date and time.
d. The output is

e.
 Some points
a. You have to take the response inside bracket only like below:
b.

c.
d. But you can take input or request without bracket also like below:
e.

f.
 The full project is
a. Setting file

b.
c. Views File:

d.
e. URL File
f.
 Important Point
a. Whenever we make any changes then compulsory server has to be restarted. But the biggest
advantage of Django is that whenever we make any changes, Django itself restarts the server so we
don’t have to do anything from our side.
b. Very rare system may not reflect the changes so very rare manually restart the server
 Single Application with Multiple Views:
 Third Project
a. Django-admin startproject thirdproject
b. Py manage.py startapp testapp
c. Add application to project in seetings.py
d. Define view functions inside views.py
e. Define url patterns
f. Run server
g. Send request
 Third Project
a. We can define any number of View Functions.
b. Whatever number of view functions you define, the same number of URLs you have to define in
application.
c. The meaning of line from testapp import views means all the views in the testapp should be available
to URL
d. User can access only those view functions for which url has bben defined.
e. Here A project contains application and a application contain viewfunctions.
f. Currently we have multiple views but we have only one application.
g. Now we want to create multiple application with single project.
 Fourth Project
a. Create fourthproject
b. Now I want to create 2 application
c. We have created 2 applications inside fourthproject i.e. (i) greetingapp (ii) timeapp
d. Now add these 2 apps inside settings.py
e. ‘+str(time)+’ has been written simultaneously to convert time into str type and then also + is for
concatenation of the string
f. Here there is only one project and 2 application. So there is only 1 url file as url file is generated
specific to project. So url for both the app should be written inside this single file only.
g. Now start the server
h. Error -why ?
i. If in url file you write: from greetingapp import views and from timeapp import views then there will
be error because 2nd statement will override the first because 2 views cannot be executed
simulataneosuly like this.
j. Solution for above problem: (i) Use Module Concept (ii) Use Aliasing
k. Use like below:
l. Solving the problem by Module concept
m.

n.
o. From greetingapp.views import greetings_view &
p. From timeapp.views import time_info_view
q. So the syntax is when we have to import two views:
r. From appname.views import view function name
s. So in the above case in URL we don’t have to write views.view function name, just simply write view
function name in url (This is the concept of the modules.) i.e. this means we dont have to write the
name of the module.
t. Above thing is like importing something from the module.
u. The other way to solve the above problem is:
v. Solving the problem by Aliasing method:

w.
x. Since you have given name v1 and v2 to views so ensure that you use these v1 and v2 names only
going forward. That’s why we ued v1.greetings_view and not views.greetings_view
y. Whenever we are developing an app, consider the reusability of the app so that we can use the same
app in multiple projects.
 Some Points
a. A application can have 100 view functions, so we have to define 100 url pattern inside urls.py.
b. This urls.py file is present at project level.
c. Now there is a project and an application is a small part of the project. Urls.py file is at project level
where all url pattern are saved.
d. This urls.py file is at project level and not part of application level.
e. Tomorrow if we want to use the application somewhere else then we can copy it but what about urls
pattern which is saved in urls.py which is part of project level.
f. Then I have to open the urls.py then I have to search the application related urls inside urls.py and
then copy paste these urls. This is tedious task. Reusability is less.
g. So solution of above problem is that we should define urls at application level instead of project level
so that when we copy the application, all the corresponding urls are also copied – this will promote
the reusability of the code.
 How to define url patterns at application level instead of project level
a. Biggest advantage of above: Application reusability is going to promoted.
b. Create a separate urls.py file at application level.
c. Link this application level urls.py to project level urls.py.

d.
e. We defined 5 views and 5 view functions are available.
f. Now we have to define 5 url patterns at project level. – don’t do that – better to take these url
patterns at application level only.
g. What we have to do:
h. In test app – do right click – new file – write the file name as urls.py while creating.Now your new
urls.py file at application level is created. (Urls.py file at project level is already present)
i. Now copy the data from project level urls.py to application level urls.py file.
j. Now include all the urls pattern written inside application level urls.py to project level urls.py file.
k. So to do this: go to urls.py file at project level write include in line from Django.conf.urls import url,
and also write testapp where we write request and include (testapp.urls) where request is mapped.
So the the full process of the point has been explained through the screenshot below:
l.

m.
n. Now testapp.urls can contain any number of urls of application level. There is no need of writing urls
pattern of application level at project level. We can simply include testapp.urls and all the urls of
application level urls.py will be included in project level urls.py.
o. You have to send the request in this case a little differently; the method is:
p.

q.
r. This means write application name/request.
s. Remember while executing this the control will first go to project level urls.py then in urls.py it will
check that testapp and testapp.urls are present so now it will go to testapp.urls i.e. urls defined at
application level urls.py. Now there it will check that any first is available (see the above command).
First is written corresponding to firstview function in url so firstview function will execute.
t. While executing the above command control will first go to project level urls.py file as this is the main
file. See in screenshot where the control will go:
u.
v.
w. Now the logic written inside project level urls.py will ensure that control goes to application level
urls.py. At application level urls.py it will access the view function according to request.
x. Also http://127.0.0.1:8000/testapp/first - see this command how the testapp and corresponding first
is executed.
y. Observe that testapp is written in request itself. So the control will go to urls.py of project file first.
Then here request word is testapp like hello or greeting of previous apps. Like hello maps with the
written view function views.Good_morning_view, similarly here testapp will maps with the include
testapp.urls. Now the flow will go to urls of testapp i.e. flow will go to urls.py of application level and
in the urls written the another requet word will be written and corresponding view function will also
be written. This another request word is also written in the request we sent to the browser. So like
first,second, third etc. are written after giving slash after testapp. Testapp/first.
 Suppose we want to use application of one project (say fifth project) to some other project (say 6 th
project)
a. The process is:
b. Copy testapp (application) of 5th project.
c. Start a new project i.e. 6th project
d. Just paste the testapp (application copied from 5th project) inside the 6th project.
e. How to use this testapp(application copied from 5 th project) inside our 6th project: You have to
perform 2 activities:
f. Activity 1: Inside the 6th project in settings.py add the application testapp
g. Activity 2: Inside urls.py(project level) of 6 th project write include etc. (which you write to include urls
at application level to the project level urls.py). The screenshot of urls.py at the project level is below:
h.

i.
j. Remember testapp.urls is written within single inverted commas.
 Advantages of defining urls at application level
a. It promotes reusability of the application
b. Project level urls.py is clean and more readable
 Till now we have done only V (View). But Django is about MVT. Now discuss T
 T (Template)
a. Till now we have provided only 1 line response to user like hello world, the current time is etc.
b. Suppose we want to provide a big table response to user or some images to user as a response.
c. So start the project:
d. This is djproject
e. Observation: Server runs specific to a project and nornamlly it does not run means your cmd should
point towards the project name then only we can run the server
f. We want some table which can store data, show some images to end user.
g. To do this in view function will take 1000s line of codes.
h. And we have to write 1000s line of code that code will be html code for creating table etc.
i. We are writing html code inside python file. This will be a tedious task.
j. So conclusion is that if you want to send just 1 or 2 lines of response then using view function is
perfect but if you want to send huge response then don’t write what you write in view. (Writing huge
html code inside python file is not a good programming practise)
k. So to overcome this problem, learn the concept of Template
l. Tempate is nothing but html file.
m. So in improved functioning the process is:
n. Whenever we are sending the request, the view function will render the html file. This means:
o. Whenever any request comes the View Function will contact the template file (results.html),
whatever response this template file gives, that response will be displayed to the end user.
p. Internally View function will ask Template file, Oye template file can you provide the required
response ? So that I (View) will display to the end user. SO template file will handover its response to
view function. Then View function will provide that response to end user.
q. The biggest advantage because of this template file is that we are not required to write html code
inside view function, total html code can be delegated to html file.
r. So We will write python code insde python file and html code inside html file.
s. The Process is explained through flowchart:
t.

u.
v. View function is going to use the template file. (Html File)
w. Who will develop template File (Html file). Answer UI expert.
x. UI developed will develop colourful response to end user.
y. The same template file can be used any number of view function. This promotes reusability of ocde.
z. Thos also ensures role separation. UI expert and Python Expert can work parallely.
aa. Mostly template file is going to be developed by UI expert.
bb. So the conclusion is:
cc. View(V) is meant for business logic (business code), Template(T) is meant for Presentation
Code(logic).
dd. M is Model. M is related with database.
ee. Tempate is used by View function to display response to end user .
ff. Template started means html started.
gg. Refer HTML, CSS and Bootstrap in full stack development course.
 Example
a. If we send a request, I want movie ratings in a table form:
b. Use template file (html) for this:
c. Change in application development:
d. These 7 steps are same
e.
f. But changes are:
g. Once we create application, Crreate one special folder template folder inside main project folder
(and not inside inner project folder). It is mandatory activity.
h. Inside this html folder, we have to take all our html files.
i. So New process with all steps is:
j.

k.
l. The Good Programming Practise:
m. We can have 100s of html(Template) file inside template file and these files will be used in various
application so there will be confusion which file is used in which application.
n. So inside template folder create a folder named with your application. So inside this application
related folder define all html files related to the application.
o. So flow of creation of project is:
p.

q.
r. It is good programming pracyise to name the application folder with application name itself.
s. If you have multiple application then create multiple folder for application.
t. In real life one project has multiple application.
u. So the full flow of process is:
v.

w.
 Project with Template (Html) File
a. Create one template folder (the exact name is templates) inside outer project older.
b. Now inside this template folder, create newfolder with name of folder as application name i.e.
testapp
c. Inside this testapp folder, you have to take all html files related to your testapp.
d. Now create template file inside this testapp folder. (This time we are creatig file and not folder) The
name of file we have put is results.html.
e. Now add template folder path inside settings.py (like we added application name)
f. The screenshot of full process is below:
g.

h.

i.
j. The full process is:

k.
l. How to add template folder path inside settings.py :
m. See in below:
 How to add template folder path inside settings.py
a. Knowledge Required to do above is:
b. If we want to know the name of the file then use command: print(__file__)
c. Our aim is to know the complete path of the file (i.e. file is located in which location) – we want
absolute path – how to do that –
d. For this there is os package there so:
e. Use following syntax:

f.
g. Here os is package, path is module, abspath means absolute path
h. So above program will give the absolute path of the file.
i. Now I want to know the directory of the file where file is available.
j. So we got the absolute path of the file. Now do os.path.dirname on this path to get the directory
name.
k. The program for finding the directory name is:
l.
m.
n. I think the name of directory is discname/foldername where the file is present.
o. Suppose I want to point to a particular folder in our computer like we want to refer the location like
d/big folder name/smaller foldername.
p. First save the directory name inside a variable of our own : BASE_DIR
q. Now inside BASE_DIR (Inside directory) there is a folder present (say templates), I want to refer to
that template folder so the way is:
r. Now join the path of BASE_DIR (Directory name) + templates (folder name which we want to refer)
s. This means we have joined the path of base directory and in that template folder. We have use join
method.
t. Now printing the Template_DIR will print the path of template folder.
u. The use of such methodology is that we never hardcoded my location.
v. Now this configuration we will use while configuring our template directory file in settings.py.
w. The Full program is:
x.

y.
 Now go in our original Project settings.py
a. We have to add template folder path in our settings.py.
b. Process with screenshot is:
c. We have to add this C:\Users\digvijay\djangoprojects\templateproject1\templates in settings.py file.
d. Add this path in settings.py after BASE_DIR by name TEMPLATE_DIR
e. This is not recommended because we are hardcoding location in our system, but if this system is run
in some other machine then digvijay folder may not be there so it is never recommended to hardcode
the system specific things.
f. So refer BASE_DIR in settings.py. BASE_DIR is already pointing upto outer templateproject1 folder
(Know this by printing BASE_DIR and executing settings.py)
g. Now extra thing required for template directory – only template directory as template directory (or
template folder) is directly inside the outer templateproject1 folder.
h. So use join method.
i. Now print Template dir also to confirm the path also. By executing settings.py
j. The screenshot is:
k.

l.
m. Screenshot for my location is:
n.
o.
p. You will line below lne for 1000 times
q. TEMPLATE_DIR = os.path.join(BASE_DIR,’Template’)
r. Observe that there is no inverted commas in BASE_DIR but there are inverted commas in Template.
(Remember that base-dir is the path we have already get and template is a folder or directory).
s. We have just created the variable which is pointing to templates.
t. You have to specify this TEMPLATE_DIR variable. Add this Template_DIR inside settings.py in that
inside TEMPLATE and inside that DIRS variable (Which is list). The screenshot for this point is below:
u.

v.
w. TEMPLATE_DIR is written in capital to indicate that it is permanent, don’t change this.
 Conclusion
a. Added testapp in the project
b. Add template dir to dir variable
c. Write template_dir inside dir of templates of settings.py
 View
a. In view, html code should not be written.
b. Html code should be written inside template file.
c. Python related business code should be written inside view.
 Django Template based applications
a. Steps covered so far:
b. Start project
c. Start application
d. Create templates folder inside outer project folder. In ths folder create testapp (application name)
folder.
e. In that testapp folder define all required template files (htnl files)
f. Add applications name in the settings.py
g. Add template folder path to settings.py
 Further Steps
a. Define business logic inside views.py
b. Meaning of line from django.shortcuts import render:
c. Django.shortcuts is a module and render is a function.
d. You have to run the serve at outer project level. This means if your cmd do not point towards outer
project folder then there will be error
 Project with screenshot
a.
b.

c.
d. But we have not used Template concept
 Using Template Concept
a. Total html code in views.py should be sent to html file.
b. Now this html code should be written to results.html file (The template file which we created inside
template folder.
c. First write html in top line select the suggestion – this will give the body code, now put the html code
inside body.
d. The screenshot is:

e.
f. Now response written in views.py is no longer required so remove that. Whatever response is there
in template file (results.html) we have to display to end user. How to get http response from this
results.html: the method is:
g. render(request, ‘testapp/results.html’)
h. Meaning of testapp/results.html: We have to access html file. The path just before testapp we have
already defined inside settings.py i.e. upto template folder so we have to define remaining path
testapp/results.html to access the html file.
i. Render is a function.
j. So we have to basically write render(request, name of template file) but since our template file is
inside testapp so we have to mention the path also.
k. So httpresponse s = render(request, ‘testapp/results.html’)
l. Return s
m. Now we are not required to write html code inside view function
n. Just to save the lines why you write s in next line directly write
o. Return render(request, ‘testapp/results.html’)
p. SO instead of first getting the response through s = HTTPResponse and then returning the response
by return s, here render function will return http response and this http response will be displayed to
user.
q. Write the code in views.py
r.
s. Since we are not using httpresponse so we can delete the 2 nd like:
t.

u.
v. Now views.py will not have html code
w. Suppose we send the request to browser, the flow will go to urls.py (project level) which will direct
the flow to views.py. Views.py file is responsible to ask - oye template file can you please provide
response. (inside view function), the code written inside view function will be sent to template file.
Then template file(results.html) will send the response to view function, view function is responsible
to display the response to the end user.
x. So be clear that response delivery is going to happen with view function only but the view function
will use template file internally to generate the response
y. Views function ask the template file to provide the required response.
z. The Full flow is:
aa.

bb.
 Now come inside html file
a. Define style tag inside head of html code
b. Code written inside the html file:
c.

d.
 Business logic is work of View and presentation logic is work of Template
 How to inject Dynamic Content from View Function to Template File
a. Dynamic content like current date and time
b. One special concept: Template Tags which also known as Template Variables.
c. By using Template Tags, we can inject dynamic contemnt from View function to htmpl (template
file).
d. The Flow is:

e.
f. Syntax to do this is below:
g. Write in view function:

h.
i. How to send dt object to template file:
j. take any variable of dict type say my_dict

k.
l. here date is key and dt is the corresponding value.
m. Add 1 more argument inside the render variable i..e. add context = my_dict inside the argument of
render function.
n. Context = my_dict means assign the my_dict (dict) to the context object.
o. My_dict is not in single quote because it is a variable name.
p. The Full code screenshot is:
q.

r.
s. Now go to html file
t. Write inside body of html file and under h2 tag: write the ….
u. Now since data is the key so write date inside two curly braces like this: {{date}}. You have to use only
the name of the variable inside curly braces.
v. So {{date}} is nothing but template tag.
w. So inside template, to inject some dynamic content, some special syntax needs to be used that
special syntax is nothing but Template Tag.
x. So write this in html file.
y. Screenshot of inside html file:
z.

aa. Meaning of Lines in View file:

bb.
cc. Through dt we are getting the dynamic content. Then through my_dict we are putting the dynamic
content in dictionary form with date as the key and dt as the corresponding value.
dd. Then through render function and context = my_dict, we are sending the dictionary to the template
file by the context object. (my_dict is the dictionary).
ee. The output will be:
ff.

gg.
hh. View is responsible to generate the dynamic content .
ii. Template is responsible to display the dynamic content . As template is meant for presentation logic
and View is responsible for business logic.
 Some information about the code.
a.

b.
c. In above image, if we remove the context and just simply write the my_dict only then also the code
will work.
d. The screenshot for that is below:

e.
f. Context was good for readability purpose but only my_dict will also work.
g. Coding hack 2:
h. Instead of writing my_dict = {‘date’:dt} and then passing the my_dict inside render function, we can
directly pass the value {‘date’:dt} inside the render function which will be sent to template file.
i. Coding Hack3:
j. You can pass any number of key values inside the render function. The code for that is:
k.

l.
m. In the above program: dt value you can find by using date variable, name value you can find by using
‘name’ variable, rollno value you can find by using ‘rollno’ variable, marks value, we can find by using
‘marks’ variable.
n. Variable date,’name’,’rollno’,marks’ are keyvalues.
o. Now open template file.
p. Write ul and then li.then write information of variable as key and its corresponding value.
q.

r.
s. ul means unordered list, li means in the unordered list, 1 st list item (li), 2nd list item (li), 3rd list item (li).
t. We are not giving any number thast why it is unordered list otherwise it would be ordered list
u. <ol> will means ordered list
v. Compulsory we must use dictionary and not any other data type like list
 Session 8
 Html code
a. Aim of this is how to display to user.
 Another Example:
a. Display current date and time and with greetings.
b. Various Step:
c.

d.
 The project
a. Inside views.py file:
b.

c.
d. Last line send the response to html (template) file.
e. Now template file is resposnsible to return http response.

f.
g. Observe that html file prepares the http response and also return the response. Above 2 lines are
proof.
h. In above two lines we are asking template file to prepare http response (in 1 st line) and return that
response to end use (in 2nd line)
i. Ensure that you return data only in dict form that’s why we used {‘msg;:msg} as dictionary
 Concept
a. If you want to send the request up to http://127.0.0.1:8000/ this only then use $ in place of hello/test
etc. in yrls.py file. The screenshot is below:
b.

c.
d. In vies.py
e.

f.
g. These are template tags.
h. This template file code is called as jinja2 code. (it is neither python nor html it is jinja 2 code).
i. Template file need not to be only 1, we can take any number of template file.
 Other languages application like java, .net, php are based on MVC design pattern. But Django is based on
MVT pattern
a. The difference b/w MVC and MVT is:
b. How MVC work:
c.

d.
e. In MVC. M is Model which handle Business Logic, V is View which handles presentation Logic, C is
Control which performs the controlling things, controllers itself do not perform any activity, it just
perform the controlling/coordinating the things. Like here controller will send the end user request to
Model and then Model will perform logic and send the response to controller but since controller do
not perform any actvivty, it just controls so controller will ask view to display/present the response
sent by Model to end user.
f. How Does MVT Work:
g. Django is based on MVT pattern
h. In MVT there is no controller so who performs the controlling activity. Answer: Django (Our
framework) itself performs the controlling activity.
i.
j.
k. Flow in MVT (Like Django)
l.

m.
n. Here Django itself is performing the controlling activities.
o. In Django or in MVT, Model(M) component is meant for Database.
 Session 11
 Working with Models(M) and Databases
 Without database, you cant expect any real time application.
 Models(M) and Database
a. How to get data from database.Store our data, read our data.
b. Database communication
c. Database is not python code, Database is outside Python.
d. Django provides inbuilt support for Database.
e. Django itself provide an inbuilt database. The name of that database is sqlite3.
f. Sqlite3 is enough for medium and small application.
 How to configure database
a. If you want to use default database sqlite3 then you are not required to configure anything.
b. But if I want to configure my own data base like MYSql then we have to mention.
c. We have to mention our database information inside settings.py . See the screenshot of stings.py.
d.

e.
 How to check if there is database support for your web application or not ?
a. Steps:
b. Go to cmd
c. How to check if database is properly configured or not ?
d. Use command (cmd pointing to outer project folder): Py manage.py shell
e.

f.
g. Above command will open Django shell
h. If there is any problem with database configuration so here you will get the error.
i. Next Command is:
j. from django.db import connection (we are importing connection object)
k. If above command does not give error this means database sqlite3 is ready to connect.
l. Now if we want to execute any query then cursor object must be required so for that use the
following command:
m. c = connection.cursor()
n. If these 3 commands are working then this means database sqlite3 is configured and you can use
that.
o. Full screenshot is:
p.

q.
 Create a table
a. Create table employees (eno number…)
b. We are not required to write single line of sql queries. How to do that:
c. For this Model Class concept is required.
d. Each model Class will represent one database table.
e. This Model Class will be converted into database table .
f. Database stuff in python is represented in Python by Model Class.
g. How to define Class:
h. (i) Inside models.py write python class.
i. Other steps are shown by creatin a modelproject1
 Creation of Modelproject1
a. Theer is one file inside testapp. The file is models.py.
b. Write below code insde models.py file:
c. Class employee(models.Model)
d. If you are writing anything inside bracket then that is parent class so models.Model is parent class
and employee is child class.
e. Class A(B): means A is child class of B.
f. Name of the table is Model.
g. Column name of table you have to specify
h. Eno = models.integerfield()
i. Ename = models.charfield
j. Esal = models.floatfield()
k. Eaddr = models.charfield()
l. We have just created 4 firlds i.e. eno, ename etc.
m. Whenever we are taking char field, we are required to pass 1 parameter. We have to pass max
length.

n.
o. This is applicable only to char field.
p. Above is not database code. It is Python code and from this code we are creating a small database
table.
q. What Model Class Contains:
r. Model Class = database table name (Employee), Columns (ename, …) and behaviour of these columns
s. Here column means field.
t. Table name = testapp_Employee
u. Fieldnames = ename, eno, esal, eaddr
v. Behavior = eno is of int type, ename is of char type, max number of allowed charcaters are 64.
w. Table_name = testapp_Employee
x. Tablename = ApplicationName_ClassName.
y. So Model is a Python Class, it represents a database table. In this table , we have field names and
their behaviour.
z. After writing model class, we have to do 2 activities:
aa. (i) MakeMigrations
bb. (ii) Migrate
cc. We wrote Python Code. For this python code, we have to generate sql code, once the sql code is
ready then execute that code, only then the database table will be created.
dd. How to convert python code into sql code – job of Makemigrations
ee. How to execute that sql code – job of Migrate Migrate is the command)
ff. If you perform these 2 activities then the database table is ready.
gg. Job of MakeMigrations – Python Model class should be converted into sql code
hh. Migrate command – sql code into database table
ii. SO commands in cmd:
jj.

kk.
ll. When we run makemigration command, one file 0001_initial.py is created inside migration folder
which is inside testapp folder.
mm. For every model, there is extra column added by Django, that extra column is ID, this act as
primary key.
nn. This id is in autoincrement mode.
oo. Id is autofield, it will be incremented by 1. For 1st record it will be 1, for 2nd record it wll be 2…. Keep
on
pp. Id will be increased by 1 for each record.
qq. ID is the new field created through above code.
rr. Autofield is always int type, it is like serial number.
ss. The file 0001_initial.py has to be converted into python code as 0001_initial.py is intermediate code.
tt. So to do that the command is:
uu. Command is:
vv. Py mange.py sqlmigrate testapp 0001
ww. Just write 0001 in place of whole 0001_initial.py.
xx. Above command will convert the code inside this file into sql code

yy.
zz. So above command will create testapp_employee table.
aaa. For every table, Django will generate a special column i.e. id. By using id we can identify each row
uniquely. Continuation below:
 Model
a. This sql code is generated by Django and not by us. i.e. Django converts python code into sql code
(Make migrations)
b. Through migrate we execute the sql code
c. Now execute the sql code through migrate command:
d. Py manage.py migrate
e. If we use migrate, multiple table will be created (as Django provides various inbuilt application like
admin, auth… so all the tables related to these applications will also be created by our migrate
command)
f. So by our migrate command, table for inbuilt application will also be created.
g. Advanatge of Migrate Command vis s vis: Creating the table Exclusively: Migrate command will also
create table for python inbuilt function also like admin, auth etc.
h. Now you can apply the following command:
i. Py manage.py migrate
j. Now database table is ready. You can see it in screenshot:
k.

l.
m. Steps done by us:

n.
o. Commands used by us till now:
p.

q.
r. Through command Py manage.py sqlmigrate testapp 0001 we get the sql code.
s. Just to check whether database is conncetd or not use below command:
t.

u.
v. After code in U, write the model class in models.py and then run the commands in point q.
w. Py manage.py sqlmigrate testapp 0001 command is just to see the generated sql code but generally
this command is not used because sql code is already generated. What will you do by seeing that
 Admin Application
a. Inbuilt application provided by Django.
b. How to launch admin interface ?
c. In the admin interface, we can check our table created,
d. In admin interface, we can perform CRUD operation on that table.
e. Through admin interface we can create, modify the records in the table
f. I want to send the request to admin. How to send that ?
g. By 127.0.0.1/admin. But if you want to access admin interface then we must know user name and
password to login in admin interface.. For this we have to createsuperuser.
h. Now run the server and send the request http://127.0.0.1:8000/admin. Immediately the browser
page will ask for user name and password.
i. So We must know the username and password to enter in admin interface. How to do this ?
j. Create superuser by the following command:
k. Py manage.py createsuperuser
l. This will show this:

m.
n. Password is Jagran@1
o. Superuser is created
p. Now run the server. Then
q. Now add the details in the web browser page which requires user name and password
r. To see our table we have to register model to Admin interface .
s. For this there is one special file is there admin.py.
t. Open admin.py and write:
u. (i) fromtestapp.models import Employee
v. (ii) admin.site.register(Employee)
w. The screenshot is:

x.
y. Here Employee is our model name.
z. Now do the process again or just refresh the browser page, you will be able to add the records in
Employee table.
 Session 12
 So the process starts by declaring model class employee inside parent class modle.model and then inside
this class you can mention the fields.
 Model is a python class which is the child class of models.model.
 Take an example

a.
b. Here employee is the model class.it should be child class of models.Model.
c. Then do field declaration etc.
 Steps to communicate with Database
a.

b.
c. Define Model Class (Here Employee is the model class)
d. Define model class by extending models.model class. (model class is child class of models.model
class)
e. Define Model class inside models.py file. (models.py file is present inside Django)
f. From Django.db import models statement is already provided by the Django.
 Next Steps
a. After creating the model class, you have to convert it to database table.
b. For that two commands are there: (i)
c. Step1: we have to convert model class create to corresponding sql code.
d. Step2: Once you create the sql code then execute that sql code, the database table will automatically
be created.
e. Py.manage.py makemigrations: it will convert python model class into corresponding sql code.
f. Py manage.py migrate: it will change the corresponding sql code into corresponding database table.

 Makemigrations command is used to generate sql code. Migrate command is used to execute that sql
code.
 In Django model class must be required. Without model class, we cannot communicate with database.
(We are not going to write sql query). Here Employee is the model class.
a. Everything like insert query, delete query etc. we will do by the model class.
b. If you want Django level benefits then communicate with database with the help of model class.
 If you want to perform database operatio. Model class must be required. We communicate with database
through Model class (Here Employee is the model class present inside models.py file)
 In above example the name of the model class is Employee.
 All the steps:
a.

b.
c.
 All The steps
a.

b.
 Django
a. In the other frameworks (other languages) if you want to add the data to table then we have to do
things like open database etc. but in Django if you want to communicate with the database, you are
not required to do these things. Directly through admin interface, you can insert the data.
b. Add the data through admin interface. (after running server and sending the admin url to browser
and then through browser which is admin interface add the data)
c. Username and password of admin interface you got when we created the superuser by the command
– py manage.py createsuperuser
d. Username : singh password: Jagran@1
 All the steps in text format
a. Define Model Class by extending models.Model class inside models.py
b. We have to register our Model to the admin inside admin.py file so that you can see your table inside
admin interface.
c. So how to do this:
d. In admin.py file write admin.site.register(Employee)
e. Through above line we are registering our model class which is employee to the admin site (admin
interface).
f. Screenshot for it.

g.
h. Also observe that we have imported Model Class (i.e.Employee) here from the testapp.
 How to open admin site/admin interface
a. Create superuser by py manage.py createsuperuser (provide username etc.)
b. How to open admin interface: http://127.0.0.1:8000/admin use this urlpattern for admin interface.
c. Now through this you can see your model in admin interface.
d. Admin application is inbuilt application of Django. Url pattern configured for admin interface is admin,
you cant use any other name, you must use admin in http://127.0.0.1:8000/admin.
e. See admin is already there in urls.py (url patterns)
f. Now run server and get this url from cmd http://127.0.0.1:8000/ now add admin in this url and send
it to browser.
g. If you do not register your model class (here Employee) in admin interface then you will not be able
to see your employee table.
 View of the data in admin interface
a.

b.
c. Currently data is seen only in Employee Object(5) form and there is no description of data is shown in
the table.
d. What to do if you want to see the description of the data added – do –
e. Whenever we are trying to print any object, to print meaningful string representation, we have to
override one method __str__ method.
f. How to define it – define this method inside the models.py file.
g. Now add details inside this instance method.Whatever details you added inside it will be displayed in
the admin interface.
h. Do this in models.py file like below:
i.

j.
k. Output will look like below:

l.
m. Now the output will be displayed in the form employee name.
n. But suppose we want that whole table should be displayed i.e. all the fields of the table should be
displayed then we have to do:
o. Go to admin.py. in it we have to define 1 special class. That special class is MA i.e. Model Class Name
followed by Admin. Here our model class name is Employee so write it like class EmployeeAdmin in
the admin.py file.
p.
q.
r. This EmployeeAdmin class is the child class of admin.ModelAdmin
s. Now display the fields which you want – use variable list_display.
t. This list_display is fixed as it is predefined word and now inside this variable you can put the fields
which you want to display with any name.
u. Now Class is completed.
v. Now register this EmployeeAdmin class also in the admin.py file. Use below command.
w.

x.
y. so we are registering two class one is model class (with name Employee) and second is modeladmin
class(i.e. employeeadmin class)
z. Observe that both the class have been defined in the same line in the same bracket separated by the
comma.
aa. Only those number of field will be displayed which you take inside the predefined variable
list_display.
bb.

cc.
dd. So the output will be:
ee.

ff.
gg. So EmployeeAdmin class decides what should be displayed in the admin interface.
hh. Click on the column in the admin interface to sort the table on the basis of that column.
ii. If you want to update the record then click the record in first column and then update that record.
jj. Till now we did only backend activity, we have not done activities like display the data to end user.
 Session 13
a. We register model class in admin interface only when we have to perform some operation in admin
interface. If we don’t have to perform any operation in admin interface then we need not to define
the model class in admin interface.
 Summary of the steps taken
a.

b.
 Superuser
a. Superuser is per project basis. Means you have to create separate superuser for each project.
b. Superuser is for username and password in admin interface.
 We do admin.site.register(classname) so that we can display our model (model data) in admin interface.
 Now our requirement is to display the data present inside the model class to the end user
a. So you have to work with views.py now.
b. You have to import Employee by command from testapp.models import Employee
c. Now we have to get the data from Employee table.
d. So sql query for it will be: select * from employees
e. The corresponding python command will be:employees = Employee.objects.all()
f. To display this data, I will send the data to template file. Command is:
g. Return render(request,’testapp/results.html’)
h. {} is dict form.
i. Data will be sent to results.html (template file)
j.

k.
l. Now create the template.
 How to create template file
a. Right click on modelproject1 and then click create new file and provide following path as you have to
create the file inside testapp
b. We have to create the file inside testapp folder that’s why we choe this path
c.

d.
e. Now write the code in template file (results.html)
f. First we have to display database information.
g. Go to results.html file and type html and select the autosuggestion of html. – this will display the full
code of html.
h. Add Template_DIR inside the settings.py file. Like below:
i.
j.
k. Also add DIRS in settings.py file like below:

l.
m. Go to results.html
n. In results.html file, we have to write templates code i.e. jinja2 codes.
o. {% %} is jinja 2 code i.e. template tag.
p. Jinja is part of Django only. When you install Django, jinja2 will be automatically installed.
q. If employees means to check if the employees are present or not.
r. Press table and select autogenerated table.
s. Type thead and select autogenerated thead and write headings of the column inside the thead.
t. For every employee again jinja2 code
u. {% for emp in employees %} is ginja 2 code.
v. For every employe 1 tr will be added. Tr is nothing but record.
w. In td we put employee number. Like this you can take other column like ename,esal,eaddr
x. So html code till now is:
y.

z.
aa. We took emp.eno inside the {{}} as this is jinja2 code and jinja2 code is written inside the {{}} quotes.
bb. For every employee separate tr will be added as tr is basically addition of a record.
cc. So for each employee a separate tr will be added.
dd. {%endfor%} is for ending the for loop and it is a jinja2 code and not python code.
ee. You can add any number of tr.
ff. Write else part after the table when no employees are found.
gg. Just type P, you will get the autosuggested paragraph, write details there.
hh. At last take {%endif%}
ii. In html code indentation is not important. We have written the code with indentation just for
readability purpose and nothing else.
jj. Indenation is required only in python(.py file)
kk. Th is the head part. I think it is for header (for doing heading).
ll. The remaining html code
mm.

nn.
oo. Take table border = 2 after if employees (as we are not using any css here)

pp.
qq. Now define the url pattern in urls.py file:
rr. In urls.py file do:

ss.
tt. Now start the server and do the remaining activities:
 Session 13: Till 29
 Default Database for Django
a. It is present in settings.py file
b.

c.
 How to setup your own database
a.

b.
c. In above image:
d. For MYSQL we have to specify the Engine.
e. In place of sqlite3, just write mysql.
f. In place of Name: specify the database name. In myql define your own database name like digvijay.db
g. User: username
h. Host: On which machine database server is running. Host = 127.0.0.1
i. Port: On which Port the database is running.
j. The screenshot for above is:
k.

l.
m. So if we provide the above information, Django will connect to provided database i.e. mysql
database.
n. This database information we have to add in settings.py file.
 Mysql database version: 8.0.27

You might also like