0% found this document useful (0 votes)
1K views53 pages

Django Application Setup Guide

The document discusses the process of creating a web application in Django, including: 1. Creating a Django project and application using commands like django-admin and manage.py startapp. 2. Configuring the application in settings.py and defining a view function in views.py to handle requests and return responses. 3. Mapping a URL pattern to the view function in urls.py so requests can be routed appropriately. 4. Running the development server and sending requests to test the application. The key files and their purposes are also summarized.

Uploaded by

kavinscrib
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1K views53 pages

Django Application Setup Guide

The document discusses the process of creating a web application in Django, including: 1. Creating a Django project and application using commands like django-admin and manage.py startapp. 2. Configuring the application in settings.py and defining a view function in views.py to handle requests and return responses. 3. Mapping a URL pattern to the view function in urls.py so requests can be routed appropriately. 4. Running the development server and sending requests to test the application. The key files and their purposes are also summarized.

Uploaded by

kavinscrib
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
  • Creation of First Web Application
  • Django Project Setup
  • Activity: Create a View
  • Http Request Flow in Django
  • How to Change Django Server Port
  • Defining URLs in Django
  • Django Templates
  • Creating a Project with Templates
  • Template Tags and Usage
  • Working with Static Files
  • Including CSS Files
  • Welcome to DURGASOFT News Portal
  • Single Project with Multiple Applications
  • Database Configuration
  • Model Class and SQL Code
  • Admin Interface and User Login
  • Faker Module and Django Forms
  • Form Validations
  • How to Prevent Bot Requests
  • Model Forms (Forms Based on Model)
  • Saving User Input to Database
  • Demo Projects
  • Template Inheritance
  • Session Management
  • Session API

db.

sqlite3

Creation of First web application:


Once we creates Django project, we can create any number of applications in that project.

The following is the command to create application.

python [Link] startapp firstApp

D:\djangoprojects\firstProject>python [Link] startapp firstApp

The following is the folder structure got created.

D:\djangoprojects>
└───firstProject
│ db.sqlite3
│ [Link]

├───firstApp
│ │ [Link]
│ │ [Link]
│ │ [Link]
│ │ [Link]
│ │ [Link]
│ │ __init__.py
│ │
│ └───migrations
│ __init__.py


6 DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | [Link]

└───firstProject
│ [Link]
│ [Link]
│ [Link]
│ __init__.py

Note: Observe that Application contains 6 files and project contains 4 files+ one special file:
[Link]

1) __init__.py:
It is a blank Python script. Because of this special name,Python treated this folder as a package.

2) [Link]:
We can register our models in this file. Django will use these models with Django's admin
interface.

3) [Link]:
In this file we have to specify application's specific configurations.

4) [Link]:
In this file we have to store application's data models.

5) [Link]:
In this file we have to specify test functions to test our code.

6) [Link]:
In this file we have to save functions that handles requests and return required responses.

7) migrations folder:
This directory stores database specific information related to models.

Note: The most important commonly used files in every project are [Link] and [Link]

Activities required for Application:


Activity-1: Add our application in [Link],so that Django aware about our application.

In [Link]:

1) INSTALLED_APPS = [
2) '[Link]',
3) '[Link]',
4) '[Link]',
5) '[Link]',


7 DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | [Link]
6) '[Link]',
7) '[Link]',
8) 'firstApp'
9) ]

Activity-2: Create a view for our application in [Link].


View is responsible to prepare required response to the end user. i.e view contains business logic.
There are 2 types of views.
1. Function Based Views
2. Class Based Views

In this application we are using Function based views.

[Link]:

1) from [Link] import render


2) from [Link] import HttpResponse
3)
4) # Create your views here.
5) def display(request):
6) s='<h1>Hello Students welcome to DURGASOFT Django classes!!!</h1>'
7) return HttpResponse(s)

Note:
1. Each view will be specified as one function in [Link].
In the above example display is the name of function which is nothing but one view.
2. Each view should take atleast one argument (request)
3. Each view should return HttpResponse object with our required response.

Diagram
View can accept request as input and perform required operations and provide proper response to
the end user.

Activity-3: Define url-pattern for our view in [Link] file.


This url-pattern will be used by end-user to send request for our views.
The 'urlpatterns' list routes URLs to views.

For functional views we have to do the following 2 activities:


1. Add an import: from firstApp import views
2. Add a URL to urlpatterns:
url(r'^greeting/', [Link])


8 DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | [Link]
[Link]:

1) from [Link] import url


2) from [Link] import admin
3) from firstApp import views
4)
5) urlpatterns = [
6) url(r'^admin/', [Link]),
7) url(r'^greetings/', [Link]),
8) ]

Whenever end user sending the request with urlpattern: greeting then disply() function will be
executed and provide required response.

Activity-4: Start Server and Send the request

py [Link] runserver

[Link]

Http Request flow in Django Application:

Diagram
1. Whenever end user sending the request first Django development server will get that request.

2. From the Request django will identify urlpattern and by using [Link], the corresponding view
will be identified.

3. The request will be forwared to the view. The corresponding function will be executed and
provide required response to the end user.

Summary of sequence of activities related to Django Project:


1) Creation of Django project
django-admin startproject firstProject


9 DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | [Link]
2) Creation of Application in that project
py [Link] startapp firstApp

3) Add application to the Project


(inside [Link])

4) Define view function inside [Link]


5) Define url-pattern for our view inside [Link]

6) Start Server
py [Link] runserver

7) Send the request

How to change Django Server Port:


By default Django develoment server will run on port number: 8000. But we can change port
number based on our requirement as follows.

py [Link] runserver 7777

Now Server running on port number: 7777


We have to send the request with this port number only

[Link]
[Link]

Defining urlpatterns at application level instead of project level:


A Django project can contain multiple applications and each application can contain multiple
[Link] url-patterns for all views of all applications inside [Link] file of project creates
maintenance problems and reduces reusability of applications.

We can solve this problem by defining url-patterns at application level instead of project level. For
every application we have to create a separate [Link] file and we have to define all that
application specific urls in that file. We have to link this application level [Link] file to project
level [Link] file by using include() method.

Demo Application:
1. Creation of Project
django-admin startproject urlProject


10 DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | [Link]
2. Creation of Application
py [Link] startapp urlApp

3. Add our application to the Project inside [Link] file

INSTALLED_APPS=[
.........
'urlApp'
]

4. Define View Function in [Link]

1) from [Link] import HttpResponse


2) def appurlinfo(request):
3)
4) s='<h1>Application Level urls Demo</h1>'
5) return HttpResponse(s)

5. Create a seperate [Link] file inside application

1) from [Link] import url


2) from urlApp import views
3) urlpatterns=[
4) url(r'^test/',[Link])
5) ]

6. Include this application level [Link] inside project level [Link] file.
from [Link]. import include

urlpatterns=[
....
url(r'^urlApp/',include('[Link]'),
]

6. Run Server
py [Link] runserver

7. Send Request
[Link]

Advantages:
The main advantages of defining urlpatterns at application level instead of project level are

1. It promotes reusability of Django Applications across multiple projects


2. Project level [Link] file will be clean and more readable


11 DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | [Link]
Django Templates:
It is not recommended to write html code inside python script ([Link] file) because:

1. It reduces readability because Python code mixed with html code

2. No seperation of roles. Python developer has to concentrate on both python code and html
code.

3. It does not promote reusability of code

We can overcome these problems by seperating html code into a seperate html [Link] html file
is nothing but template.
From the Python file ([Link] file) we can use these templates based on our requirement.

We have to write templates at project level only once and we can use these in multiple
applications.

Python stuff required to develop Template Based Application:


1. To know the current Python file name
print(__file__) #[Link]

2. To know absolute path of current Python File Name


import os
print([Link](__file__))

Output: D:\durgaclasses\[Link]

3. To know Base Directory name of the current file


print([Link]([Link](__file__)))
Output: D:\durgaclasses

4. Inside D:\durgaclasses there is one folder named with templates. To know its absolute path

import os
BASE_DIR=[Link]([Link](__file__))
TEMPLATE_DIR=[Link](BASE_DIR,'templates')
print(TEMPLATE_DIR)

Output: D:\durgaclasses\templates

Note: The main advantage of this approach is we are not required to hard code system specific
paths(locations) in our python script.

Steps to develop Template Based Application:



12 DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | [Link]
1. Creation of Project
django-admin startproject templateProject

2. Creation of Application
py [Link] startapp testApp

3. Add this application to the project in [Link] file,so that Django aware of application

4. Create a 'templates' folder inside main project folder.


In that templates folder create a seperate folder named with testApp to hold that particular
application specific templates.

5. Add templates folder to [Link] file so that Django can aware of our templates.

TEMPLATES = [
{
...,
'DIRS': ['D:\djangoprojects\templateProject\templates'],

},]

It is not recommended to hard code system specific locations in [Link] file. To overcome this
problem, we can generate templates directory path programatically as follows.

import os

BASE_DIR = [Link]([Link]([Link](__file__)))
TEMPLATE_DIR=[Link](BASE_DIR,'templates')

Specify this TEMPLATE_DIR inside [Link] as follows

TEMPLATES = [
{
...,
'DIRS': [TEMPLATE_DIR,],

},]

6. Create html file inside templateProject/templates/testApp folder. This html file is nothing but
template.

[Link]:

1) <!DOCTYPE html>
2) <html lang="en" dir="ltr">
3) <head>
4) <meta charset="utf-8">
5) <title>First Template Page</title>
6) </head>


13 DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | [Link]
7) <body>
8) <h1>Hello welcome to Second Hero of MVT: Templates</h1>
9) </body>
10) </html>

7. Define Function based view inside [Link] file

1) from [Link] import render


2) def wish(request):
3) return render(request,'testApp/[Link]')

8. Define URL Pattern either at application level or at project level

9. Run server and send request

Template Tags:
From Python [Link] we can inject dynamic content to the template file by using template tags.

Template Tags also known as Template Variables.

Take special care about Template tag syntax it is not python syntax and not html syntax. Just it is
special syntax.

Template tag syntax for inserting text data:


{ {insert_date} }

This template tag we have to place inside template file (ie html file) and we have to provide
insert_date value from python [Link] file.

Diagram
Demo Application to send date and time from [Link] to template file:

[Link]:

1) <!DOCTYPE html>
2) <html lang="en" dir="ltr">
3) <head>
4) <meta charset="utf-8">
5) <title>First Template Page</title>


14 DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | [Link]
6) <style >
7) h1{
8) color:white;
9) background: red;
10) }
11) </style>
12) </head>
13) <body>
14) <h1>Hello Server Current Date and Time : <br>
15) {{insert_date}}
16) </h1>
17) </body>
18) </html>

[Link]:

1) from [Link] import render


2) import datetime
3) def wish(request):
4) date=[Link]()
5) my_dict={'insert_date':date}
6) return render(request,'testApp/[Link]',context=my_dict)

Note: The values to the template variables should be passed from the view in the form of
dictionary as argument to context.

Application to wish end user based on time:


[Link]:

1) <!DOCTYPE html>
2) <html lang="en" dir="ltr">
3) <head>
4) <meta charset="utf-8">
5) <title>First Template Page</title>
6) <style >
7) #h11{
8) color:red;
9) }
10) #h12{
11) color:green;
12) }
13) </style>
14) </head>
15) <body>
16) <h1 id=h11>{{insert_msg}}</h1>
17) <h1 id=h12>Current Date and Time : {{insert_date}}</h1>
18) </body>


15 DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | [Link]
19) </html>

[Link]:

1) from [Link] import render


2) import datetime
3)
4) # Create your views here.
5) def wish(request):
6) date=[Link]()
7) msg='Hello Guest !!!! Very Very Good '
8) h=int([Link]('%H'))
9) if h<12:
10) msg +='Morning!!!'
11) elif h<16:
12) msg +='AfterNoon!!!'
13) elif h<21:
14) msg +='Evening!!!'
15) else:
16) msg='Hello Guest !!!! Very Very Good Night!!!'
17) my_dict={'insert_date':date,'insert_msg':msg}
18) return render(request,'testApp/[Link]',context=my_dict)

Working with Static Files:


Up to this just we injected normal text data into template by using template tags.

But sometimes our requirement is to insert static files like images,css files etc inside template file.

Process to include static files inside template:


1. Create a folder named with 'static' inside main project folder. It is exactly same as creating
'templates' folder.
In that 'static' folder create 'images' folder to place image files.

2. Add static directory path to [Link] file, so that Django can aware of our images.

[Link]:

1) STATIC_DIR=[Link](BASE_DIR,'static')
2)
3) ..
4) STATIC_URL = '/static/'
5)
6) STATICFILES_DIRS=[
7) STATIC_DIR,
8) ]


16 DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | [Link]
3. Make sure all paths are correct or not

[Link]

4. Use Template Tags to insert image


At the beginning of html just after <!DOCTYPE html> we have to include the following template
tag

{% load staticfiles %}

Just we are conveying to the Django to load all static files.

We have to include image file as follows


<img src="{% static "images/[Link]"% }">

[Link]:

1) <!DOCTYPE html>
2) {% load staticfiles %}
3) <html lang="en" dir="ltr">
4) <head>
5) <meta charset="utf-8">
6) <title>First Template Page</title>
7) <style >
8) #h11{
9) color:red;
10) }
11) #h12{
12) color:green;
13) }
14) </style>
15) </head>
16) <body>
17) <h1 id=h11>{{insert_msg}}</h1>
18) <h1 id=h12>Current Date and Time : {{insert_date}}</h1>
19) <h1>This climate preferable image is:</h1>
20) <img src="{% static "images/[Link]" %}" alt="">
21) </body>
22) </html>

[Link]:

1) from [Link] import render


2) import datetime
3)
4) # Create your views here.
5) def wish(request):
6) date=[Link]()
7) msg=None


17 DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | [Link]
8) h=int([Link]('%H'))
9) if h<12:
10) msg='Hello Guest !!!! Very Very Good Morning!!!'
11) elif h<16:
12) msg='Hello Guest !!!! Very Very Good AfterNoon!!!'
13) elif h<21:
14) msg='Hello Guest !!!! Very Very Good Evening!!!'
15) else:
16) msg='Hello Guest !!!! Very Very Good Night!!!'
17) my_dict={'insert_date':date,'insert_msg':msg}
18) return render(request,'testApp/[Link]',context=my_dict)

How to include css file:


1. Create a folder 'css' inside static and place our [Link] file in that css folder.

[Link]:

1) img{
2) height: 500px;
3) width: 500px;
4) border: 10px red groove;
5) margin:0% 20%;
6) }
7) h1{
8) color:blue;
9) text-align: center;
10) }

2. In the template html file we have to include this css file. We have to do this by using link tag
inside head tag.

<link rel="stylesheet" href="{% static "css/[Link]" %}" >

DURGASOFT NEWS PORTAL:


[Link]:


18 DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | [Link]
1) <!DOCTYPE html>
2) {% load staticfiles%}
3) <html lang="en" dir="ltr">
4) <head>
5) <meta charset="utf-8">
6) <title></title>
7) <link rel="stylesheet" href="{% static "css/[Link]"%}">
8) </head>
9) <body>
10) <h1>Welcome to DURGASOFT NEWS PORTAL</h1>
11) <ul>
12) <li> <a href="/movies">Movies Information</a> </li>
13) <li> <a href="/sports">Sports Information</a> </li>
14) <li> <a href="/politics">Politics Information</a> </li>
15) </ul>
16) </body>
17) </html>

[Link]:

1) <!DOCTYPE html>
2) {% load staticfiles %}
3) <html lang="en" dir="ltr">
4) <head>
5) <meta charset="utf-8">
6) <title></title>
7) <link rel="stylesheet" href="{% static "css/[Link]"%}">
8) </head>
9) <body>
10) <h1>{{head_msg}}</h1>
11) <ul>
12) <li> <h2>{{sub_msg1}}</h2> </li>
13) <li> <h2>{{sub_msg2}}</h2> </li>
14) <li> <h2>{{sub_msg3}}</h2> </li>
15) </ul>
16) <img src="{% static "images/[Link]" %}" alt="">
17) <img src="{% static "images/[Link]" %}" alt="">
18) <img src="{% static "images/[Link]" %}" alt="">
19) </body>
20) </html>

[Link]:

1) from [Link] import render


2)
3) # Create your views here.

19 DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | [Link]
4) def moviesInfo(request):
5) my_dict={'head_msg':'Movies Information',
6) 'sub_msg1':'Sonali slowly getting cured',
7) 'sub_msg2':'Bahubali-3 is just planning',
8) 'sub_msg3':'Salman Khan ready to marriage',
9) 'photo':'images/[Link]'}
10) return render(request,'[Link]',context=my_dict)
11) def sportsInfo(request):
12) my_dict={'head_msg':'Sports Information',
13) 'sub_msg1':'Anushka Sharma Firing Like anything',
14) 'sub_msg2':'Kohli updating in game anything can happend',
15) 'sub_msg3':'Worst Performance by India-Sehwag',
16) }
17) return render(request,'[Link]',context=my_dict)
18) def politicsInfo(request):
19) my_dict={'head_msg':'Politics Information',
20) 'sub_msg1':'Achhce Din Aaa gaya',
21) 'sub_msg2':'Rupee Value now 1$:70Rs',
22) 'sub_msg3':'In India Single Paisa Black money No more',
23) }
24) return render(request,'[Link]',context=my_dict)
25) def index(request):
26) return render(request,'[Link]')

[Link]:

1) import os
2)
3) BASE_DIR = [Link]([Link]([Link](__file__)))
4) TEMPLATES_DIR=[Link](BASE_DIR,'templates')
5) STATIC_DIR=[Link](BASE_DIR,'static')
6)
7) INSTALLED_APPS = [
8) '[Link]',
9) '[Link]',
10) '[Link]',
11) '[Link]',
12) '[Link]',
13) '[Link]',
14) 'newsApp'
15) ]
16)
17) TEMPLATES = [
18) {
19) '
20) 'DIRS': [TEMPLATES_DIR,],
21)
22) ],
23) },


20 DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | [Link]
24) },
25) ]
26)
27) STATIC_URL = '/static/'
28) STATICFILES_DIRS=[
29) STATIC_DIR,
30) ]

[Link]:

1) from [Link] import url


2) from [Link] import admin
3) from newsApp import views
4)
5) urlpatterns = [
6) url(r'^admin/', [Link]),
7) url(r'^movies/', [Link]),
8) url(r'^sports/', [Link]),
9) url(r'^politics/', [Link]),
10) url(r'^$', [Link]),
11) ]

Single Project with Multiple applications:


[Link]:

1) from [Link] import url


2) from [Link] import admin
3) from firstApp import views as v1
4) from secondApp import views as v2
5)
6) urlpatterns = [
7) url(r'^admin/', [Link]),
8) url(r'^firstwish/', v1.wish1),
9) url(r'^secondwish/', v2.wish2),
10) ]

Working with Models and Databases:


As the part of web application development, compulsory we required to interact with database to
store our data and to retrieve our stored data.

Django provides a big in-built support for database operations. Django provides one inbuilt
database sqlite3.
For small to medium applications this database is more enough. Django can provide support for
other databases also like oracle, mysql,postgresql etc


21 DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | [Link]
Database configuration:
Django by default provides sqlite3 database. If we want to use this database,we are not required
to do any configurations.

The default sqllite3 configurations in [Link] file are declared as follows.

[Link]:

1) DATABASES = {
2) 'default': {
3) 'ENGINE': '[Link].sqlite3',
4) 'NAME': [Link](BASE_DIR, 'db.sqlite3'),
5) }
6) }

If we don't want sqlite3 database then we have to configure our own database with the following
parameters.

1. ENGINE: Name of Database engine


2. NAME: Database Name
3. USER: Database Login user name
4. PASSWORD: Database Login password
5. HOST: The Machine on which database server is running
6. PORT: The port number on which database server is running

Note: Most of the times HOST and PORT are optional.

How to check django database connection:


We can check whether django database configurations are properly configured or not by using the
following commands from the shell

D:\djangoprojects\modelProject>py [Link] shell


> from [Link] import connection
> c=[Link]()

If we are not getting any error means our database configurations are proper.

Configuration of mysql database:


First we have to create our own logical database in the mysql.

mysql> create database employeedb;



22 DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | [Link]
We have to install mysqlclient by using pip as follows

pip install --only-binary :all: mysqlclient

[Link]:

1) DATABASES = {
2) 'default': {
3) 'ENGINE': '[Link]',
4) 'NAME': 'employeedb',
5) 'USER':'root',
6) 'PASSWORD':'root'
7) }
8) }

Checking configurations:
D:\djangoprojects\modelProject>py [Link] shell
> from [Link] import connection
> c=[Link]()

Configuration of Oracle database:


1) DATABASES = {
2) 'default': {
3) 'ENGINE': '[Link]',
4) 'NAME': 'XE',
5) 'USER':'scott',
6) 'PASSWORD':'tiger'
7) }
8) }

Note: We can find oracle database name by using the following command.

SQL> select * from global_name;

Model Class:
⚽ A Model is a Python class which contains database information.
⚽ A Model is a single, definitive source of information about our data. It contains fields and
behavior of the data what we are storing.
⚽ Each model maps to one database table.
⚽ Every model is a Python class which is the child class of ([Link])
⚽ Each attribute of the model represents a database field.
⚽ We have to write all model classes inside ‘[Link]’ file.


23 DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | [Link]
1. Create a project and application and link them.

django-admin startproject modelProject


cd modelProject/
python [Link] startapp testApp

After creating a project and application, in the [Link] file, write the following code:

[Link]:

1) from [Link] import models


2)
3) # Create your models here.
4)
5) class Employee([Link]):
6) eno=[Link]()
7) ename=[Link](max_length=30)
8) esal=[Link]()
9) eaddr=[Link](max_length=30)

Note: This model class will be converted into Database table. Django is responsible for this.

table_name: appName_Employee
fields: eno, ename, esal and eaddr. And one extra field: id
behaviors: eno is of type Integer, ename is of type Char and max_length is 30 characters.

Hence,

Model Class = Database Table Name + Field Names + Field Behaviors

Converting Model Class into Database specific SQL Code:


Once we write Model class, we have to generate the corresponding SQL Code. For this, we have to
use “makemigrations” command.

Python [Link] make migrations

It results the following :


Migrations for 'testApp':
testApp/migrations/0001_initial.py
- Create model Employee

How to see corresponding sql code of migrations:


To see the generated SQL Code, we have to use the following command “sqlmigrate”


24 DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | [Link]
python [Link] sqlmigrate testApp 0001

1) BEGIN;
2) --
3) -- Create model Employee
4) --
5) CREATE TABLE "testApp_employee" ("id" integer NOT NULL PRIMARY KEY AUTOINCREME
NT, "eno" integer NOT NULL, "ename" varchar(30) NOT NULL, "esal" real NOT NULL, "eadd
r" varchar(30) NOT NULL);
6) COMMIT;

Note: Here 0001 is the file passed as an argument

“id” field:
1. For every table(model), Django will generate a special column named with “id”.
2. ID is a Primary Key. (Unique Identifier for every row inside table is considered as a primary key).
3. This field(id) is auto increment field and hence while inserting data, we are not required to
provide data for this field.
4. This id field is of type “AutoField”
5. We can override the behavior of “id” field and we can make our own field as “id”.
6. Every Field is by default “NOT NULL”.

How to execute generated SQL code (migrate command):


After generating sql code, we have to execute that sql code to create table in database. For this,
we have to use ‘migrate’ command.

python [Link] migrate

Operations to perform:
Apply all migrations: admin, auth, contenttypes, sessions, testApp
Running migrations:
Applying contenttypes.0001_initial... OK
Applying auth.0001_initial... OK
Applying admin.0001_initial... OK
Applying admin.0002_logentry_remove_auto_add... OK
Applying contenttypes.0002_remove_content_type_name... OK
Applying auth.0002_alter_permission_name_max_length... OK
Applying auth.0003_alter_user_email_max_length... OK
Applying auth.0004_alter_user_username_opts... OK
Applying auth.0005_alter_user_last_login_null... OK
Applying auth.0006_require_contenttypes_0002... OK
Applying auth.0007_alter_validators_add_error_messages... OK
Applying auth.0008_alter_user_username_max_length... OK
Applying sessions.0001_initial... OK
Applying testApp.0001_initial... OK

Note: Now tables will be created in the database.


25 DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | [Link]
What is the advantage of creating tables with ‘migrate’ Command
If we use ‘migrate’ command, then all Django required tables will be created in addition to our
application specific tables. If we create table manually with sql code, then only our application
specific table will be created and django my not work properly. Hence it is highly recommended to
create tables with ‘migrate’ command.

How to check created table in django admin interface:


We have to register model class in ‘[Link]’ file.

[Link]:

1) from [Link] import admin


2) from [Link] import Employee
3)
4) # Register your models here.
5)
6) [Link](Employee)

Creation of super user to login to admin interface:


We can create super user with the following command by providing username, mailid, password.

python [Link] createsuperuser

We can login to admin interface → Start the server and login to admin interface using the created
credentials.

python [Link] runserver

Open the following in browser:


[Link]

Difference between makemigrations and migrate:


“makemigrations” is responsible to generate SQL code for Python model class whereas “migrate”
is responsible to execute that SQL code so that tables will be created in the database.

To display data in admin interface in browser:


[Link]:

1) from [Link] import models


2)
3) # Create your models here.


26 DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | [Link]
4)
5) class Employee([Link]):
6) eno=[Link]()
7) ename=[Link](max_length=30)
8) esal=[Link]()
9) eaddr=[Link](max_length=30)
10)
11) def __str__(self):
12) return 'Employee Object with eno: +str([Link])'

[Link]:

1) from [Link] import admin


2) from [Link] import Employee
3)
4) # Register your models here.
5)
6) class EmployeeAdmin([Link]):
7) list_display=['eno','ename','esal','eaddr']
8)
9) [Link](Employee,EmployeeAdmin)

Now we can write views to get data from the database and send to template.
Before writing [Link] file, create “templates” and “static” folder with respective application
folders and HTML and CSS files and link them in [Link] file.

[Link]:

1) from [Link] import render


2) from [Link] import Employee
3)
4) # Create your views here.
5) def empdata(request):
6) emp_list=[Link]()
7) my_dict={'emp_list':emp_list}
8) return render(request, 'testApp/[Link]', context=my_dict)

[Link]

1) <!DOCTYPE html>
2) {% load staticfiles %}
3) <html lang="en" dir="ltr">
4) <head>
5) <meta charset="utf-8">
6) <title></title>
7) <link rel="stylesheet" href="{% static '/css/[Link]'%}">
8) </head>
9)
10) <body>


27 DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | [Link]
11) <h1> The employees list is : </h1>
12)
13) {% if emp_list %}
14) <table>
15) <thead>
16) <th> eno </th>
17) <th> ename </th>
18) <th> esal </th>
19) <th> eaddr </th>
20) </thead>
21)
22) {% for emp in emp_list %}
23) <tr>
24) <td> {{[Link]}}</td>
25) <td>{{[Link]}}</td>
26) <td>{{[Link]}}</td>
27) <td> {{[Link]}}</td>
28) </tr>
29) {% endfor %}
30)
31) </table>
32) {%else%}
33) <p> No records found </p>
34) {% endif %}
35)
36) </body>
37) </html>

MVT Diagram:
FAQs:
How to configure database inside [Link]?
How to check connections?
How to define Model class inside [Link]
How we can perform makemigrations?
How we can perform migrate?
How to add our model to admin interface inside [Link]
To display total data how to write ModelAdmin class inside [Link]
how to createsuperuser?
How to login to admin interface and add data to our tables?
How to see generated sqlcode b'z of makemigrations


28 DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | [Link]
Faker Module:
We can use Faker Module to generate fake data for our database models.

1) from faker import Faker


2) from random import *
3) fakegen=Faker()
4) name=[Link]()
5) print(name)
6) first_name=fakegen.first_name()
7) last_name=fakegen.last_name()
8) print(first_name)
9) print(last_name)
10) date=[Link]()
11) print(date)
12) number=fakegen.random_number(5)
13) print(number)
14) email=[Link]()
15) print(email)
16) print([Link]())
17) print(fakegen.random_int(min=0, max=9999))
18) print(fakegen.random_element(elements=('Project Manager', 'TeamLead', 'Software Engin
eer')))

Note: Working with mysql db(studentinfo project)

Django Forms:
It is the very important concept in web development.
The main purpose of forms is to take user input.

Eg: login form, registration form, enquiry form etc

From the forms we can read end user provided input data and we can use that data based on
requirement. We may store in the database for future purpose. We may use just for
validation/authentication purpose etc

Here we have to use Django specific forms but not HTML forms.

Advantages of Django Forms over HTML forms:


1. We can develop forms very easily with python code
2. We can generate HTML Form widgets/components (like textarea, email, pwd etc) very quickly
3. Validating data will become very easy
4. Processing data into python data structures like list, set etc will become easy
5. Creation of Models based on forms will become easy etc.


29 DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | [Link]
Process to generate Django forms:
Step-1: Creation of [Link] file in our application folder with our required fields.

[Link]:

1) from django import forms


2) class StudentForm([Link]):
3) name=[Link]()
4) marks=[Link]()

Note: name and marks are the field names which will be available in html form

Step-2: usage of [Link] inside [Link] file:

[Link] file is responsible to send this form to the template html file

[Link]:

1) from [Link] import render


2) from . import forms
3)
4) # Create your views here.
5) def studentinputview(request):
6) form=[Link]()
7) my_dict={'form':form}
8) return render(request,'testapp/[Link]',context=my_dict)

# alternative short way:

1) def studentinputview(request):
2) form=[Link]()
3) return render(request,'testapp/[Link]',{'form':form})

Note: context parameter is [Link] can pass context parameter value directly without using
keyword name 'context'

Step-3: Creation of html file to hold form:

Inside template file we have to use template tag to inject form

{{form}}

It will add only form fields. But there is no <form> tag and no submit button.
Even the fields are not arranged [Link] is ugly form.

We can make proper form as follows


30 DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | [Link]
1) <h1>Registration Form</h1>
2) <div class="container" align="center">
3) <form method="post">
4) {{form.as_p}}
5) <input type="submit" class="btn btn-primary" name="" value="Submit">
6) </form>
7)
8) </div>

[Link]:

1) <!DOCTYPE html>
2) {%load staticfiles%}
3) <html lang="en" dir="ltr">
4) <head>
5) <meta charset="utf-8">
6) <link rel="stylesheet" href="{%static "css/[Link]"%}">
7) <link rel="stylesheet" href="{%static "css/[Link]"%}">
8) <title></title>
9) </head>
10) <body>
11) <h1>Registration Form</h1>
12) <div class="container" align="center">
13) <form method="post">
14) {{form.as_p}}
15) <input type="submit" class="btn btn-primary" name="" value="Submit">
16) </form>
17) </div>
18) </body>
19) </html>

If we submit this form we will get 403 status code response


Forbidden (403)
CSRF verification failed. Request aborted.

Help
Reason given for failure:

CSRF token missing or incorrect.

Every form should satisfy CSRF (Cross Site Request Forgery) Verification, otherwise Django won't
accept our form.
It is meant for website security. Being a programmer we are not required to worry anything about
this. Django will takes care everything.
But we have to add csrf_token in our form.

1) <h1>Registration Form</h1>
2) <div class="container" align="center">
3) <form method="post">


31 DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | [Link]
4) {{form.as_p}}
5) {% csrf_token %}
6) <input type="submit" class="btn btn-primary" name="" value="Submit">
7) </form>
8) </div>

If we add csrf_token then in the generate form the following hidded field will be added,which
makes our post request secure

<input type='hidden' name='csrfmiddlewaretoken'


value='1ZqIJJqTLMVa6RFAyPJh7pwzyFmdiHzytLxJIDzAkKULJz4qHcetLoKEsRLwyz4h'/>

The value of this hidden field is keep on changing from request to [Link] it is impossible to
forgery of our request.

If we configured csrf_token in html form then only django will accept our form.

How to process input data from the form inside [Link] file:
We required to modify [Link] file. The end user provided input is available in a dictionary
named with 'cleaned_data'

[Link]:

1) from [Link] import render


2) from . import forms
3)
4) # Create your views here.
5) def studentinputview(request):
6) form=[Link]()
7) if [Link]=='POST':
8) form=[Link]([Link])
9) if form.is_valid():
10) print('Form validation success and printing data')
11) print('Name:',form.cleaned_data['name'])
12) print('Marks:',form.cleaned_data['marks'])
13) return render(request,'testapp/[Link]',{'form':form})


32 DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | [Link]
project: formproject

Student FeedBack Form Project


[Link]:

1) from django import forms


2)
3) class FeedBackForm([Link]):
4) name=[Link]()
5) rollno=[Link]()
6) email=[Link]()
7) feedback=[Link](widget=[Link])

[Link]:

1) from [Link] import render


2) from . import forms
3)
4) def feedbackview(request):
5) form=[Link]()
6) if [Link]=='POST':
7) form=[Link]([Link])
8) if form.is_valid():
9) print('Form Validation Success and printing information')
10) print('Name:',form.cleaned_data['name'])
11) print('Roll No:',form.cleaned_data['rollno'])
12) print('Email:',form.cleaned_data['email'])
13) print('FeedBack:',form.cleaned_data['feedback'])
14) return render(request,'testapp/[Link]',{'form':form})

[Link]:

1) <!DOCTYPE html>
2) {% load staticfiles%}
3) <html lang="en" dir="ltr">
4) <head>
5) <meta charset="utf-8">
6) <link rel="stylesheet" href="[Link]
[Link]" integrity="sha384-
BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossori
gin="anonymous">
7) <link rel="stylesheet" href="{% static "css/[Link]" %}">
8) <title></title>
9) </head>
10) <body>
11) <div class="container" align='center'>
12) <h1>Student Feedback Form</h1><hr>


33 DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | [Link]
13) <form class="" action="[Link]" method="post">
14) {{form.as_p}}
15) {% csrf_token %}
16) <input type="submit" class="btn btn-primary" value="Submit Feedback">
17) </form>
18) </div>
19) </body>
20) </html>

Form Validations:
Once we submit the form we have to perform validations like
1. Length of the field should not be empty
2. The max number of characters should be 10
3. The first character of the name should be 'd' etc

We can implement validation logic by using the following 2 ways.

1. Explicitly by the programmer by using clean methods


2. By using Django inbuilt validators

Note: All validations should be implemented in the [Link] file

1. Explicitly by the programmer by using clean methods:


The syntax of clean method:

clean_fieldname(self)

In the FormClass for any field if we define clean method then at the time of submit the form,
Django will call this method automatically to perform validations. If the clean method won't raise
any error then only form will be submitted.

1) from django import forms


2)
3) class FeedBackForm([Link]):
4) name=[Link]()
5) rollno=[Link]()
6) email=[Link]()
7) feedback=[Link](widget=[Link])
8)
9) def clean_name(self):
10) inputname=self.cleaned_data['name']
11) if len(inputname) < 4:


34 DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | [Link]
12) raise [Link]('The Minimum no of characters in the name field should
be 4')
13) return inputname

The returned value of clean method will be considered by Django at the time of submitting the
form.

[Link]:

1) from django import forms


2) from [Link] import validators
3)
4) class FeedBackForm([Link]):
5) name=[Link]()
6) rollno=[Link]()
7) email=[Link]()
8) feedback=[Link](widget=[Link])
9)
10) def clean_name(self):
11) print('validating name')
12) inputname=self.cleaned_data['name']
13) if len(inputname) < 4:
14) raise [Link]('The Minimum no of characters in the name field should
be 4')
15) return inputname+'durga'
16) def clean_rollno(self):
17) inputrollno=self.cleaned_data['rollno']
18) print('Validating rollno field')
19) return inputrollno
20) def clean_email(self):
21) inputemail=self.cleaned_data['email']
22) print('Validating email field')
23) return inputemail
24)
25) def clean_feedback(self):
26) inputfeedback=self.cleaned_data['feedback']
27) print('Validating feedback field')
28) return inputfeedback

server console:
validating name
Validating rollno field
Validating email field
Validating feedback field
Form Validation Success and printing information
Name: Durgadurga
Roll No: 101
Email: durgaadvjava@[Link]
FeedBack: This is sample feedback


35 DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | [Link]
Note:
1 .Django will call these filed level clean methods automatically and we are not required to call
explicitly.

2. Form validation by using clean methods is not recommended.

2. Django's inbuilt core validators:


Django provides several inbuilt core validators to perform very common validations. We can use
these validators directly and we are not required to implement.

Django's inbuilt validators are available in the [Link] module.

from [Link] import validators

To validate Max number of characters in the feedback as 40,we have to use inbuilt validators as
follows.

[Link]:

1) from django import forms


2) from [Link] import validators
3)
4) class FeedBackForm([Link]):
5) name=[Link]()
6) rollno=[Link]()
7) email=[Link]()
8) feedback=[Link](widget=[Link],validators=[[Link]
dator(40)])

Note: We can use any number of validators for the same field

feedback=[Link](widget=[Link],validators=[[Link](40),
[Link](10)])

Note: Usage of built in validators is very easy when compared with clean methods.

How to implement custom validators by using the same validator parameter:

The value of name parameter should starts with 'd' or 'D'. We can implement this validation as
follows

1) def starts_with_d(value):
2) if value[0].lower() != 'd':
3) raise [Link]('Name should be starts with d | D')
4)
5) class FeedBackForm([Link]):


36 DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | [Link]
6) name=[Link](validators=[starts_with_d])
7) rollno=[Link]()

Validation of total form directly by using a single clean method:


Whenever we are submitting the form Django will call clean() method present in our Form class. In
that method we can implement all validations.

[Link]:

1) from django import forms


2) from [Link] import validators
3)
4) class FeedBackForm([Link]):
5) name=[Link]()
6) rollno=[Link]()
7) email=[Link]()
8) feedback=[Link](widget=[Link])
9)
10) def clean(self):
11) print('Total Form Validation...')
12) total_cleaned_data=super().clean()
13) inputname=total_cleaned_data['name']
14) if inputname[0].lower() != 'd':
15) raise [Link]('Name parameter should starts with d')
16) inputrollno=total_cleaned_data['rollno']
17) if inputrollno <=0:
18) raise [Link]('Rollno should be > 0')

How to check original pwd and reentered pwd are same or not:
[Link]:

1) from django import forms


2) from [Link] import validators
3)
4) class FeedBackForm([Link]):
5) name=[Link]()
6) password=[Link](widget=[Link])
7) rpassword=[Link](label='Re Enter Password',widget=[Link])
8) rollno=[Link]()
9) email=[Link]()
10) feedback=[Link](widget=[Link])
11)
12) def clean(self):
13) print('validating passwords match...')
14) total_cleaned_data=super().clean()
15) fpwd=total_cleaned_data['password']


37 DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | [Link]
16) spwd=total_cleaned_data['rpassword']
17) if fpwd != spwd:
18) raise [Link]('Both passwords must be matched')

How to prevent requests from BOT:


Generally form requests can be send by end user. Sometimes we can write automated
programming script which is responsible to fill the form and submit. This automated programming
script is nothing but BOT.

The main objectives of BOT requests are:

1. To create unnecessary heavy traffic to the website, which may crash our application

2. To spread malware (viruses)

Being web developer compulsory we have to think about BOT requests and we have to prevent
these requests.

How to prevent BOT Requests:


In the form we will place one hidden form field, which is not visible to the end user. Hence there is
no chance of providing value to this hidden field.

But BOT will send the value for this hidden field [Link] hidden field got some value means it is the
request from BOT and prevent that form submission.

1) from django import forms


2) from [Link] import validators
3)
4) class FeedBackForm([Link]):
5) name=[Link]()
6) password=[Link](widget=[Link])
7) rpassword=[Link](label='Re Enter Password',widget=[Link])
8) rollno=[Link]()
9) email=[Link]()
10) feedback=[Link](widget=[Link])
11) bot_handler=[Link](required=False,widget=[Link])
12)
13) def clean(self):
14) print('validating passwords match...')
15) total_cleaned_data=super().clean()


38 DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | [Link]
16) fpwd=total_cleaned_data['password']
17) spwd=total_cleaned_data['rpassword']
18) if fpwd != spwd:
19) raise [Link]('Both passwords must be matched')
20) bot_handler_value=total_cleaned_data['bot_handler']
21) if len(bot_handler_value)>0:
22) raise [Link]('Request from BOT...cannot be submitted!!!')

Notes with bot field:


1) class FeedBackForm([Link]):
2) normal fields..
3) bot_handler=[Link](required=False,widget=[Link])
4)
5) def clean(self):
6) total_cleaned_data=super().clean()
7) bot_handler_value=total_cleaned_data['bot_handler']
8) if len(bot_handler_value)>0:
9) raise [Link]('Request from BOT...cannot be submitted!!!')

Note: Other ways to prevent BOT requests


1. By using Captchas
2. By using image recognizers
(like choose 4 images where car present)
Note:
Other way to create project
py -m django startproject modelformproject

Model Forms (Forms based on Model):


Sometimes we can create form based on Model, such type of forms are called model based forms
or model forms.

The main advantage of model forms is we can grab end user input and we can save that input data
very easily to the database.

Django provides inbuilt support to develop model based forms very easily.

How to develop Model based forms:


1. While develop FormClass instead of inheriting [Link] class,we have to inherit
[Link] class.

class RegisterForm([Link]):
....


39 DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | [Link]
2. We have to write one nested class (Meta class) to specify Model information and required
fields.

class RegisterForm([Link]):
# field declarations if we are performing any custom [Link] we are not defining any
custom validations then here we are not required to specify any field.

class Meta:
# we have to specify Model class name and requied fields
model=Student
fields='__all__'

Case-1: Instead of all fields if we want only selected fields,then we have to specify as follows

class Meta:
model=Student
fileds=('field1','field2','field3')

In the form only 3 fields will be considered.


If Model class contains huge number of fields and we required to consider very less number of
fields in the form then we should use this approach.

Case-2:

Instead of all fields if we want to exclude certain fields,then we have to specify as follows

class Meta:
model=Student
exclude=['field1','field2']

In the form all fields will be considered except field1 and field2.

If the Model class contains huge number of fields and if we want to exclude very few fields then
we have to use this approach.

Q. In Model based forms, how many ways are there to


specify fields information
Ans: 3 ways
1. All fields
2. Include certain fields
3. Exclude certain fields

Note: The most commonly used approach is to include all fields.


40 DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | [Link]
How to save user's input data to database in Model based
forms:
We have to use save() method.

def student_view(request):
...
if [Link]=='POST':
form=RegisterForm([Link])
if form.is_valid():
[Link](commit=True)
..

Demo project-1 (modelformproject):


[Link]:

1) from [Link] import models


2)
3) # Create your models here.
4) class Student([Link]):
5) name=[Link](max_length=30)
6) marks=[Link]()

[Link]:

1) from django import forms


2) from [Link] import Student
3) class StudentForm([Link]):
4) #fields with validations
5) class Meta:
6) model=Student
7) fields='__all__'

[Link]:

1) from [Link] import render


2) from . import forms
3)
4) # Create your views here.
5) def student_view(request):
6) form=[Link]
7) if [Link]=='POST':
8) form=[Link]([Link])
9) if form.is_valid():
10) [Link](commit=True)

41 DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | [Link]
11) return render(request,'testapp/[Link]',{'form':form})

Demo Project-2: movieproject


Advanced Templates:
1. Template Inheritance
2. Template Filters
3. Template tags for relative urls

1. Template Inheritance:
If multiple template files have some common code,it is not recommended to write that common
code in every template html file. It increases length of the code and reduces readability. It also
increases development time.

We have to seperate that common code into a new template file,which is also known as base
template. The remaining template files should required to extend base template so that the
common code will be inherited automatically.

Inheriting common code from base template to remaining templates is nothing but template
inheritance.

How to implement template inheritane:


[Link]:

1) <!DOCTYPE html>
2) html,css,bootstrap links
3) <body>
4) common code required for every child tempalte
5) {% block child_block%}
6) Anything outside of this block available to child tag.
7) in child template the specific code should be in this block
8) {%endblock%}
9) </body>
10) </html>

[Link]:

1) <!DOCTYPE html>
2) {%extends 'testapp/[Link]'%}
3) {% block child_block %}
4) child specific extra code
5) {%endblock%}


42 DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | [Link]
Demo program: advtempproject
[Link]:

1) <!DOCTYPE html>
2) {%load staticfiles%}
3) <html lang="en" dir="ltr">
4) <head>
5) <meta charset="utf-8">
6) <link rel="stylesheet" href="[Link]
[Link]" integrity="sha384-
BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossori
gin="anonymous">
7) <link rel="stylesheet" href="{%static "css/[Link]"%}">
8) <title></title>
9) </head>
10) <body>
11) <nav class="navbar navbar-default navbar-fixed-top navbar-inverse">
12) <div class="container-fluid">
13)
14) <div class="navbar-header">
15) <a class="navbar-brand" href="/">DURGA NEWS</a>
16) </div>
17) <ul class="nav navbar-nav">
18) <li class="active"><a href="/">Home <span class="sr-
only">(current)</span></a></li>
19) <li><a href="/movies">Movies</a></li>
20) <li><a href="/sports">Sports</a></li>
21) <li><a href="/politics">Politics</a></li>
22) </ul>
23) </div><!-- /.container-fluid -->
24) </nav>
25) <div class="container">
26) {%block body_block%}
27) <!-- outside of this block everything available to child tempaltes -->
28) {%endblock%}
29) </div>
30) </body>
31) </html>

[Link]:

1) <!DOCTYPE html>
2) {%extends 'testapp/[Link]'%}
3) {% block body_block %}
4) <br><br><br><br><br><br>
5) <h1>Welcome to DURGA NEWS PORTAL</h1>
6) {%endblock%}


43 DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | [Link]
[Link]:

1) <!DOCTYPE html>
2) {%extends 'testapp/[Link]'%}
3) {% block body_block %}
4) <br><br><br>
5) <h1>Sports Information</h1>
6) {%endblock%}

Advantages of Template Inheritance:


1. What ever code available in base template is by default available to child templates and we are
not required to write [Link] it promotes Code Reusability (DRY)

2. It reduces length of the code and improves readability

3. It reduces development time

4. It provides unique and same look and feel for total web application.

Note: Based on our requirement we can extend any number of base templates.i.e Multiple
Inheritance is applicable for templates.

Tempalte Filters:
In the template file, the injected data can be displayed by using template tags.

{{[Link]}}

Before displaying to the end user if we want to perform some modification to the injected text,
like cut some information or converting to title case etc,then we should go for Template filters.

Syntax of Template Filter:


{{value|filtername:"argument"}}

Filter may take or may not take arguments.i.e arguments are optional.

Eg:
<li>{{msg1|lower}}</li>
msg1 will be displayed in lower case

<li>{{msg3|add:"Durga"}}</li>
"Durga" will be added to msg3 and then display the result to the end user

{{ msg|title }}


44 DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | [Link]
{{ my_date|date:"Y-m-d" }}

Note: There are tons of built in filters are available.

[Link]

How to create our own filter:


Based on our requirement we can create our own filter.

Steps:

1. Create a folder 'templatetags' inside our application folder

2. Create a special file named with __init__.py inside templatetags folder, so that Django will
consider this folder as a valid python package

3. Create a python file inside templatetags folder to define our own filters

cust_filters.py -->any name

cust_filters.py:

1) from django import template


2) register=[Link]()
3)
4) def first_eight_upper(value):
5) '''''This is my own filter'''
6) result=value[:8].upper()
7) return result
8)
9) [Link]('f8upper',first_eight_upper)

Note: We can also register filter with the decorator as follows.

1) from django import template


2) register=[Link]()
3)
4) @[Link](name='f8upper')
5) def first_eight_upper(value):
6) '''''This is my own filter'''
7) result=value[:8].upper()
8) return result

f8upper is the name of the filter which can be used inside template file.


45 DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | [Link]
4. Inside template file we have to load the filter file as follows(In the child template bunot in base
template)

{%load cust_filters%}

5. We can invoke the filter as follows

{{msg|f8upper}}

[Link]:

1) <!DOCTYPE html>
2) {%extends 'testapp/[Link]'%}
3) {% block body_block %}
4) <h1>Movies Information</h1><hr>
5) {%load cust_filters%}
6) <ul>
7) <li>{{msg1|lower}}</li>
8) <li>{{msg2|upper}}</li>
9) <li>{{msg3|add:"--Durga"}}</li>
10) <li>{{msg4|f8upper}}</li>
11) <li>{{msg5}}</li>
12) </ul>
13) {%endblock%}

Eg 2: Custom Filter with argument


@[Link](name='c_and_c')
def cut_and_concate(value,arg):
result=value[:4]+str(arg)
return result

Note: The main advantage of template filters is we can display the same data in different styles
based on our requirement.

advtemp project

Template Tags for URLs:


<a href='testapp1/thankyou'>Thank You </a>

<a href="{% url 'thankyou' %}">Thank You </a>

<a href="{% url '[Link]' %}">Thank You </a>

<a href="{% url 'testapp:thankyou' %}">Thank You </a>

Session Management:

46 DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | [Link]
Client and Server can communicate with some common language which is nothing but HTTP.

The basic limitation of HTTP is, it is stateless protocol. i.e it is unable to remember client
information for future purpose across multiple requests. Every request to the server is treated as
new request.

Hence some mechanism must be required at server side to remember client information across
multiple [Link] mechanism is nothing but session management mechanism.

The following are various session management mechanisms.

1. Cookies
2. Session API
3. URL Rewriting
4. Hidden Form
Fields etc

Session Management By using Cookies:


Cookie is a very small amount of information created by Server and maintained by client.

Diagram
Whenever client sends a request to the server,if server wants to remember client information for
the future purpose then server will create cookie object with the required information. Server will
send that Cookie object to the client as the part of response. Client will save that cookie in its local
machine and send to the server with every consecutive request. By accessing cookies from the
request server can remember client information.


47 DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | [Link]
How to test our browser supports Cookies or not:
We have to use the following 3 methods on the request object.

1. set_test_cookie()
2. test_cookie_worked()
3. delete_test_cookie()

[Link]:

1) from [Link] import render


2) from [Link] import HttpResponse
3)
4) # Create your views here.
5) def index(request):
6) [Link].set_test_cookie()
7) return HttpResponse('<h1>index Page</h1>')
8)
9) def check_view(request):
10) if [Link].test_cookie_worked():
11) print('cookies are working properly')
12) [Link].delete_test_cookie()
13) return HttpResponse('<h1>Checking Page</h1>')

Note: Before executing this program compulsory we should perform migrate.

Session Management by using Cookies:


[Link]:

1) from [Link] import render


2)
3) # Create your views here.
4) def count_view(request):
5) if 'count' in [Link]:
6) newcount=int([Link]['count'])+1
7) else:
8) newcount=1
9) response=render(request,'testapp/[Link]',{'count':newcount})
10) response.set_cookie('count',newcount)
11) return response

[Link]:

1) <!DOCTYPE html>
2) <html lang="en" dir="ltr">
3) <head>


48 DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | [Link]
4) <meta charset="utf-8">
5) <title></title>
6) <style >
7) span{
8) font-size: 200px;
9) font-weight: 900;
10) }
11)
12) </style>
13) </head>
14) <body>
15) <h1>Page Count is: <span> {{count}}<span></h1>
16) </body>
17) </html>

Session Management by using Cookies Demo Program-3:


1) from [Link] import render
2) from [Link] import LoginForm
3) import datetime
4)
5) # Create your views here.
6) def home_view(request):
7) form=LoginForm()
8) return render(request,'testapp/[Link]',{'form':form})
9)
10) def date_time_view(request):
11) # form=LoginForm([Link])
12) name=[Link]['name']
13) response=render(request,'testapp/[Link]',{'name':name})
14) response.set_cookie('name',name)
15) return response
16)
17) def result_view(request):
18) name=[Link]['name']
19) date_time=[Link]()
20) my_dict={'name':name,'date_time':date_time}
21) return render(request,'testapp/[Link]',my_dict)

[Link]:

1) <!DOCTYPE html>
2) <html lang="en" dir="ltr">
3) <head>
4) <meta charset="utf-8">
5) <title></title>
6) </head>
7) <body>


49 DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | [Link]
8) <h1>Welcome to DURGASOFT</h1>
9) <form action="/second">
10) {{form.as_p}}
11) {%csrf_token%}
12) <input type="submit" name="" value="Enter Name">
13) </form>
14) </body>
15) </html>

[Link]:

1) <!DOCTYPE html>
2) <html lang="en" dir="ltr">
3) <head>
4) <meta charset="utf-8">
5) <title></title>
6) </head>
7) <body>
8) <h1>Hello {{name}}</h1> <hr>
9) <a href="/result">Click Here to get Date and Time</a>
10) </body>
11) </html>

[Link]:

1) <!DOCTYPE html>
2) <html lang="en" dir="ltr">
3) <head>
4) <meta charset="utf-8">
5) <title></title>
6) </head>
7) <body>
8) <h1>Hello {{name}}</h1><hr>
9) <h1>Current Date and Time:{{date_time}}</h1>
10) <a href="/result">Click Here to get Updated Date and Time</a>
11) </body>
12) </html>

Cookie Example-4:

Diagram

50 DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | [Link]
[Link]:

1) from [Link] import render


2)
3) # Create your views here.
4) def name_view(request):
5) return render(request,'testapp/[Link]')
6)
7) def age_view(request):
8) name=[Link]['name']
9) response=render(request,'testapp/[Link]',{'name':name})
10) response.set_cookie('name',name)
11) return response
12)
13) def gf_view(request):
14) age=[Link]['age']
15) name=[Link]['name']
16) response=render(request,'testapp/[Link]',{'name':name})
17) response.set_cookie('age',age)
18) return response
19)
20) def results_view(request):
21) name=[Link]['name']
22) age=[Link]['age']
23) gfname=[Link]['gfname']
24) response=render(request,'testapp/[Link]',{'name':name,'age':age,'gfname':gfnam
e})
25) response.set_cookie('gfname',gfname)
26) return response

[Link]:

1) <!DOCTYPE html>
2) <html lang="en" dir="ltr">
3) <head>
4) <meta charset="utf-8">
5) <title></title>
6) </head>
7) <body>
8) <h1>Welcome to DURGASOFT</h1>
9) <form action='/age'>
10) Enter Name: <input type="text" name="name" value=""><br><br>
11) <input type="submit" name="" value="Submit Name">
12) </form>
13)
14) </body>
15) </html>

[Link]:

51 DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | [Link]
1) <!DOCTYPE html>
2) <html lang="en" dir="ltr">
3) <head>
4) <meta charset="utf-8">
5) <title></title>
6) </head>
7) <body>
8) <h1>Hello {{name}}..</h1><hr>
9) <form action='/gf'>
10) Enter Age: <input type="text" name="age" value=""><br><br>
11) <input type="submit" name="" value="Submit Age">
12) </form>
13) </body>
14) </html>

[Link]:

1) <!DOCTYPE html>
2) <html lang="en" dir="ltr">
3) <head>
4) <meta charset="utf-8">
5) <title></title>
6) </head>
7) <body>
8) <h1>Hello {{name}}..</h1><hr>
9)
10) <form action='/results'>
11) Enter Girl Friend Name: <input type="text" name="gfname" value=""><br><br>
12) <input type="submit" name="" value="Submit GFName">
13) </form>
14)
15) </body>
16) </html>

[Link]:

1) <!DOCTYPE html>
2) <html lang="en" dir="ltr">
3) <head>
4) <meta charset="utf-8">
5) <title></title>
6) </head>
7) <body>
8) <h1>Hello {{name}} Thanks for providing info</h1>
9) <h2>Please cross check your data and confirm</h2><hr>
10) <ul>
11) <li>Name:{{name}}</li>
12) <li>Age:{{age}}</li>
13) <li>Girl Friend Name:{{gfname}}</li>


52 DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | [Link]
14) </ul>
15) </body>
16) </html>

Limitations of Cookies:
1. By using cookies we can store very less amount of information. The size of the cookie is
[Link] if we want to store huge amount of information then cookie is not best choice.

2. Cookie can hold only string information. If we want to store non-string objects then we should
not use cookies.

3. Cookie information is stored at client side and hence there is no security

4. Everytime with every request, browser will send all cookies related to that application,which
creates network traffic problems.

5. There is a limit on the max number of cookies supported by browser.

To overcome all these limitations we should go for sessions.

Temporary vs Permanent Cookies:


If we are not setting any max_age for the cookie,then the cookies will be stored in browsers
[Link] we closed browser automatically the cookies will be [Link] type of cookies are
called temporary Cookies.

We can set temporary Cookie as follows:


response.set_cookie(name,value)

If we are setting max_age for the cookie,then cookies will be stored in local file system
[Link] the specified max_age expires then only cookies will be [Link] type of
cookies are called permanent or persistent cookies. We can set Permanent Cookies as follows

response.set_cookie(name,value,max_age=180)
response.set_cookie(name,value,180)

The time unit for max_age is in seconds.

Demo Program-3:
[Link]:

1) from [Link] import render


2) from [Link] import ItemAddForm
3)


53 DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | [Link]
4) # Create your views here.
5) def index(request):
6) return render(request,'testapp/[Link]')
7) def additem(request):
8) form=ItemAddForm()
9) response=render(request,'testapp/[Link]',{'form':form})
10) if [Link]=='POST':
11) form=ItemAddForm([Link])
12) if form.is_valid():
13) name=form.cleaned_data['itemname']
14) quantity=form.cleaned_data['quantity']
15) response.set_cookie(name,quantity,180)
16) # return index(request)
17) return response
18) def displayitem_view(request):
19) return render(request,'testapp/[Link]')

[Link]:

1) <!DOCTYPE html>
2) <html lang="en" dir="ltr">
3) <head>
4) <meta charset="utf-8">
5) <!-- Latest compiled and minified CSS -->
6) <link rel="stylesheet" href="[Link]
[Link]" integrity="sha384-
BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossori
gin="anonymous">
7) <title></title>
8) </head>
9) <body>
10) <div class="container" align='center'>
11) <div class="jumbotron">
12) <h1>DURGASOFT ONLINE SHOPPING APP</h1>
13) <a class="btn btn-primary btn-lg" href="/add" role="button">ADD ITEM</a>
14) <a class="btn btn-primary btn-lg" href="/display" role="button">Display ITEMS</a>
15) </div>
16)
17) </div>
18) </body>
19) </html>

[Link]:

1) <!DOCTYPE html>
2) <html lang="en" dir="ltr">
3) <head>
4) <meta charset="utf-8">
5) <title></title>


54 DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | [Link]
6) <link rel="stylesheet" href="[Link]
[Link]" integrity="sha384-
BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossori
gin="anonymous">
7) </head>
8) <body>
9) <div class="container" align='center'>
10) <h1>Add Item Form</h1>
11) <form method="post">
12) {{form.as_p}}
13) {%csrf_token%}
14) <input type="submit" name="" value="Add Item">
15) </form><br><br><br>
16) <a class="btn btn-primary btn-lg" href="/display" role="button">Display ITEMS</a>
17) </div>
18) </body>
19) </html>

[Link]:

1) <!DOCTYPE html>
2) <html lang="en" dir="ltr">
3) <head>
4) <meta charset="utf-8">
5) <title></title>
6) </head>
7) <body>
8) <h1>Total Cookies Information:</h1>
9) {%if [Link] %}
10) <table border=2>
11) <thead>
12) <th>Cookie Name</th>
13) <th>Cookie Value</th>
14) </thead>
15)
16) {% for key,value in [Link] %}
17) <tr>
18) <td>{{key}}</td>
19) <td>{{value}}</td>
20) </tr>
21) {% endfor %}
22) </table>
23) {%else%}
24) <p>Cookie Information is not available</p>
25) {%endif%}
26) </body>
27) </html>


55 DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | [Link]
Session Management By using Session API:
(Django Session Framework)

Diagram
Once client sends request to the server,if server wants to remember client information for the
future purpose then server will create session object and store required information in that
object. For every session object a unique identifier available which is nothing but sessionid. Server
sends the corresponding session id to the client as the part of response. Client retrieves the
session id from the response and save in the local file system. With every consecutive request
client will that session id. By accessing that session id and corresponding session object server can
remember client. This mechanism is nothing but session management by using session api.

Note: Session information will be stored in one of following possibilities

1. Inside a File
2. Inside a database
3. Inside Cache

The most straight forward approach is to use [Link] application to store session
information in a Django Model/database.

The Model Name is:


[Link]

Note: To use this approach compulsory the following applicaiton should be configured inside
INSTALLED_APPS list of [Link] file.

[Link]

If it is not there then we can add,but we have to synchronize database


python [Link] syncdb

Note:

INSTALLED_APPS = [
....
'[Link]',


56 DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | [Link]
...
]

MIDDLEWARE = [
..
'[Link]',
....
]

Useful Methods for session Management:


1. [Link]['key']=value
To add data to the session

2. value=[Link]['key']
To get data from the session

3. [Link].set_expiry(seconds)
Sets the expiry time for the session

4. [Link].get_expiry_age()
returns the expiry age in seconds(the number of seconds until this session expire)

5. [Link].get_expiry_date()
Returns the data on which this session will expire

Note: Before using session object in our application,compulsory we have to migrate. otherwise
we will get the following error.
no such table: django_session

Session Demo1:
[Link]:

1) from [Link] import render


2)
3) # Create your views here.
4) def page_count_view(request):
5) count=[Link]('count',0)
6) newcount=count+1
7) [Link]['count']=newcount
8) print([Link].get_expiry_age())
9) print([Link].get_expiry_date())
10) return render(request,'testapp/[Link]',{'count':newcount})

[Link]:


57 DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | [Link]
1) <!DOCTYPE html>
2) <html lang="en" dir="ltr">
3) <head>
4) <meta charset="utf-8">
5) <title></title>
6) <style >
7) span{
8) font-size: 300px;
9) }
10)
11) </style>
12) </head>
13) <body>
14) <h1>The Page Count:<span>{{count}}</span></h1>
15) </body>
16) </html>


58 DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | [Link]

db.sqlite3
Creation of First web application:
Once we creates Django project, we can create any number of applications in tha
│
└───firstProject
│settings.py
│urls.py
│wsgi.py
│__init__.py
│
Note: Observe that Application contains 6 files and project
6)
'django.contrib.messages',
7)
'django.contrib.staticfiles',
8)
'firstApp'
9)
]
Activity-2: Create a view for our applicati
urls.py:
1)
from django.conf.urls import url
2)
from django.contrib import admin
3)
from firstApp import views
4)
5)
urlpatte
2)
Creation of Application in that project 
py manage.py startapp firstApp
3)
Add application to the Project
(inside settings
2. Creation of Application
py manage.py startapp urlApp
3. Add our application to the Project inside settings.py file
INSTALL
Django Templates:
It is not recommended to write html code inside python script (views.py file) because:
1. It reduces readab
1. Creation of Project
django-admin startproject templateProject
2. Creation of Application
py manage.py startapp testApp
3.
7)
<body>
8)
<h1>Hello welcome to Second Hero of MVT: Templates</h1>
9)
</body>
10) </html>
7. Define Function based view ins
6)
<style >
7)
h1{
8)
color:white;
9)
background: red;
10)
}
11)
</style>
12) </head>
13) <body>
14)
<h1>Hello Server Current

You might also like