100% found this document useful (1 vote)
3K views14 pages

Python Django Complete PDF

Download as pdf or txt
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 14

https://pythonschoolkvs.wordpress.

com/
CLASS-XII
COMPUTER SCIENCE-PYTHON (083)

UNIT-III DATA MANAGEMENT-2 (Django)


By: Vikash Kumar Yadav
PGT-Computer Science
K.V. No.-IV ONGC Vadodara
3.1 Django:

 Django is a free and open source web application framework written in


Python.
 It is based on Model-View-Controller (MVC) framework.
 It is used for developing the web application.

3.2 Installation of Django:

 Install Python 3.5 or upper version


 Connect your computer with internet and open Command Prompt & type the
following command to install Django:
pip install django
 For verification of installation of Django. Open Command prompt and type the
following command:
django-admin - -version
It will display the installed version in computer.

3.3 Prepare the machine to develop the web Application:

 After installation of Python and Django in computer, next step is install the
IDE (Integrated Development Environment) to write the code for web
application. Here, we shall use PyCharm as IDE.
 PyCharm : PyCharm is an IDE used in computer programming, specifically for
the Python language.
 To download PyCharm, go to the following link:
https://www.jetbrains.com/pycharm/download/
 Install the setup.
 Now your system is ready to develop a web application in PyCharm using
Django.

https://pythonschoolkvs.wordpress.com/ Page 1
3.4 Create a Project and web application:

 After Installation of PyCharm IDE, open command prompt window.


 Go to the directory where you want to create the project. Here, we shall
create the project in D:\ drive.
 To create the project type the following command in command prompt.
D:\>django-admin startproject SPORTSMEET

Here SPORTSMEET is the name of Project. A folder with the name


SPORTSMEET will be created in D:\ directory.

 Now start PyCharm, Click on File OpenSPORTSMEET folder in D:\ drive


OK
 SPORTSMEET project will be opened in PyCharm. It will have SPORTSMEET
subfolder and manage.py file.
 SPORTSMEET subfolder has the following files:
o __init__.py
o settings.py
o urls.py
o wsgi.py
 Now open the Terminal window in PyCharm. Go to the directory
D:\SPORTSMEET>

 Create the application under SPORTSMEET Project. Here the application name
is NATIONALS. To create this application, type the following command in
terminal window of PyCharm.
D:\SPORTSMEET>python manage.py startapp NATIONALS

 Now to start the Django server, Type following command in Terminal window
of PyCharm.
D:\SPORTSMEET>python manage.py runserver

 After successfully execution of above command, it will provide an address,


which is given below:
http://127.0.0.1:8000/
Copy the above link and paste it in web browser. The following screen will
appear in your web browser. It means Django server is working properly.

https://pythonschoolkvs.wordpress.com/ Page 2
So, we have created a project SPORTSMEET and a web application NATIONALS under
this project.

 In this web application we will perform the CRUD (Create, Read, Update,
Delete) operations.
 We shall store the data of those students who will participate in National
Sports Meet and perform the CRUD operations with the data stored in
database.
 To Store the data, we will use sqlite3 database system which is in-built in
PyCharm. So no need to install it separately. You can use MySQL database
system, which we will discuss later.

3.5 Now start the coding:

 Open PyCharm.
 Open settings.py file under SPORTSMEET subfolder to add our application in
installed apps for migration.
Example:
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'NATIONALS'
]

https://pythonschoolkvs.wordpress.com/ Page 3
 Open the file models.py under NATIONALS web application to create a model
and its fields. Models are considered as tables in MVC framework. An
application may have multiple models.
from django.db import models

class PLAYER(models.Model):
pid = models.CharField(max_length=10)
pname = models.CharField(max_length=50)
dob = models.CharField(max_length=20)
gender = models.CharField(max_length=10)
game = models.CharField(max_length=30)
region = models.CharField(max_length=35)
class Meta:
db_table = 'player'

 Here, class Meta is as an instance of class PLAYER, that executes with Meta
class.
 Now create a file forms.py under NATIONALS by right click on NATIONALS.

Django provides the facility of forms. It means we need not create any HTML
form for table fields. Django denotes the table fields as a form. For that we
have to create a forms.py file and write the following code in forms.py file.

https://pythonschoolkvs.wordpress.com/ Page 4
from django import forms
from NATIONALS.models import PLAYER
class PLAYERFORM (forms.ModelForm):
class Meta:
model = PLAYER
fields = "__all__"

 Now migrate the models in database. For this, we have to run the following
commands in Terminal window of PyCharm:
D:\SPORTSMEET>python manage.py makemigrations
This command will create the model and make the changes if any. If the
command successfully runs, the following information will be displayed in
Terminal window.
Migrations for 'NATIONALS':
NATIONALS\migrations\0001_initial.py
- Create model PLAYER
 Now run another command to migrate the created model. In Terminal
window, write the following command:
D:\SPORTSMEET>python manage.py migrate

Now the created model is stored in the file 0001_initial.py under the folder
migration in NATIONALS application.

 A table player has been created in database. It has following fields:


(id, pid, pname, DOB, gender, game, region). id field is automatically created
in Django, which has its own system generated values.
 Create a folder named as templates under the application NATIONALS.

https://pythonschoolkvs.wordpress.com/ Page 5
templates folder will have the .html files. In our application, we will have
index.html, edit.html and show.html files under templates folder.
 Create the html files with the name index.html, edit.html and show.html, by
right click on templates folder under NATIONALS.

 Create another folder with the name static, under NATIONALS. It will have
style.css file.
Right click on static folderNewFilewrite the name style.cssOK
Write following code in style.css file:
table, th, td {
border: 1px solid black;
}

div {
font-weight:bold;
}

 Now, open views.py under the application NATIONALS.


 views.py file will work as a controller. It is not the view in MVC. In this file we
would call the view according to their actions. In this file, we will also work
with models. So, it is an important file.
 Write the following code in views.py file:
from django.shortcuts import render, redirect
from NATIONALS.forms import PLAYERFORM
from NATIONALS.models import PLAYER

https://pythonschoolkvs.wordpress.com/ Page 6
# Create your views here.
def ply(request):
if request.method == "POST":
form = PLAYERFORM(request.POST)
if form.is_valid():
try:
form.save()
return redirect('/show')
except:
pass
else:
form = PLAYERFORM()
return render(request,"index.html",{'form':form})

def show(request):
players = PLAYER.objects.all()
return render(request,"show.html",{'players':players})

def edit(request, id):


player = PLAYER.objects.get(id=id)
return render(request, "edit.html", {'player': player})

def update(request, id):


player = PLAYER.objects.get(id=id)
form = PLAYERFORM(request.POST, instance= player)
if form.is_valid():
form.save()
return redirect('/show')
return render(request, "edit.html", {'player': player})

def delete (request, id):


player = PLAYER.objects.get(id=id)
player.delete()
return redirect('/show')

 Open index.html file under templates folder and write the following code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Index Page</title>
{% load staticfiles %}
<link rel="stylesheet" href="{% static '/style.css' %}" />
</head>
<body>
<center><strong><u><h1>PLAYER DATA</h1></u></strong></center>
<center>

<form method = "POST" class = "post-form" action="/ply">


{% csrf_token %}
<div class="container">

https://pythonschoolkvs.wordpress.com/ Page 7
<br>
<div class = "form-group row">
<label class="col-sm-1 col-form-label"></label>
<div class="col-sm-4">
<h3>Enter Details</h3>
</div>

</div>
<div class = "form-group row" >
<label class="col-sm-2 col-form-label">Player ID:
</label>&nbsp; &nbsp; &nbsp;
{{ form.pid }}
</div>
<br>

<div class = "form-group row" >


<label class="col-sm-2 col-form-label">Player Name:
</label>
{{ form.pname }}
</div>
<br>

<div class = "form-group row" >


<label class="col-sm-2 col-form-label">Date of
Birth: </label>
{{ form.dob }}
</div>
<br>

<div class = "form-group row">


<label class="col-sm-2 col-form-label">Gender:
</label>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
{{ form.gender }}
</div>
<br>

<div class = "form-group row">


<label class="col-sm-2 col-form-label">Game:
</label>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
{{ form.game }}
</div>
<br>

<div class = "form-group row">


<label class="col-sm-2 col-form-label">Region:
</label>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
{{ form.region }}
</div>
<br>

<div class = "form-group row">


<label class="col-sm-1 col-form-label"> </label>
<div class="col-sm-4">

https://pythonschoolkvs.wordpress.com/ Page 8
<button type="submit" class="btn btn-
primary">Submit</button>
</div>
</div>
</div>

</form></center>
</body>
</html>

 Open show.html file under templates folder and write the following code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Show Player Details</title>
{% load staticfiles %}
<link rel = "stylesheet " href="{% static '/style.css' %}"
/>
</head>
<body>
<center><strong><u><h1>PLAYER
DETAILS</h1></u></strong></center>
<center>
<table class="table table-striped table-bordered table=80%">
<thead class= "thead-dark">
<tr>
<th>Player ID</th>
<th>Player Name</th>
<th>Date of Birth</th>
<th>Gender</th>
<th>Game</th>
<th>Region</th>
<th colspan="2">Action</th>
</tr>
</thead>
<tbody>
{% for player in players %}
<tr>
<td>{{ player.pid }}</td>
<td>{{ player.pname }}</td>
<td>{{ player.dob }}</td>
<td>{{ player.gender }}</td>
<td>{{ player.game }}</td>
<td>{{ player.region }}</td>
<td>
<a href = "/edit/{{player.id}}"><span
class="glyphicon glyphicon-pencil">Edit</span> </a>
</td>
<td>
<a href="/delete/{{player.id}}">Delete</a>
</td>

https://pythonschoolkvs.wordpress.com/ Page 9
</tr>
{% endfor %}
</tbody>
</table>
</center>
<br>
<br>
<center><a href="/ply" class="btn btn-primary">Add New
Record</a></center>

</body>
</html>

 Open edit.html file under templates folder and write the following code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title> Edit Record </title>
{% load staticfiles %}
<link rel = "stylesheet" href = "{% static '/style.css' %}"
/>
</head>
<body>
<center>
<form method="POST" class="post-form"
action="/update/{{player.id}}" >
{% csrf_token %}
<div class ="container">
<br>
<div class="form-group row">
<label class="col-sm-1 col-form-label"></label>
<div class = "col-sm-4">
<h3>Update Details</h3>
</div>
</div>
<br>

<div class="form-group row">


<label class="col-sm-2 col-form-label">Player ID :
</label>&nbsp;&nbsp;&nbsp;&nbsp;
<input type="text" name="pid" id="id_pid" required
maxlength="10" value="{{player.pid}}"/>
</div>
<br>

<div class="form-group row">


<label class="col-sm-2 col-form-label">Player Name
: </label>
<input type="text" name="pname" id="id_pname"
required maxlength="50" value="{{player.pname}}"/>
</div>

https://pythonschoolkvs.wordpress.com/ Page 10
<br>

<div class="form-group row">


<label class="col-sm-2 col-form-label">DOB :
</label>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
<input type="text" name="dob" id="id_dob"
required maxlength="20" value="{{player.dob}}"/>
</div>
<br>

<div class="form-group row">


<label class="col-sm-2 col-form-label">Gender :
</label>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
<input type="text" name="gender" id="id_gender"
required maxlength="10" value="{{player.gender}}"/>
</div>
<br>

<div class="form-group row">


<label class="col-sm-2 col-form-label">Game :
</label>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
<input type="text" name="game" id="id_game"
required maxlength="30" value="{{player.game}}"/>
</div>
<br>

<div class="form-group row">


<label class="col-sm-2 col-form-label">Region :
</label>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
<input type="text" name="region" id="id_region"
required maxlength="35" value="{{player.region}}"/>
</div>
<br>

<div class="form-group row">


<label class="col-sm-1 col-form-label"></label>
<div class="col-sm-4">
<button type="submit" class="btn btn-
success">Update</button>
</div>
</div>

</div>
</form>
</center>
</body>
</html>

 Open urls.py under SPORTSMEET subfolder. And refer the methods. Write
the following code in urls.py file.

https://pythonschoolkvs.wordpress.com/ Page 11
from django.contrib import admin
from django.urls import path
from NATIONALS import views

urlpatterns = [
path('admin/', admin.site.urls),
path('ply', views.ply),
path('show', views.show),
path('edit/<int:id>', views.edit),
path('update/<int:id>', views.update),
path('delete/<int:id>', views.delete),

]
 After that save the project. Now open Terminal window in PyCharm, Write
the following command:
D:\SPORTSMEET>Python manage.py runserver
After execution of above command, the following address will appear in
Terminal window.
http://127.0.0.1:8000/
Copy it and paste it into web browser. Press Enter. It will display the error
page. Now write the address of the show page. Means, write the address
given below:
http://127.0.0.1:8000/show

OUTPUTS:

https://pythonschoolkvs.wordpress.com/ Page 12
OUTPUT-1 Empty Table, No Records

OUTPUT-2 Adding the New Record

https://pythonschoolkvs.wordpress.com/ Page 13
OUTPUT-3 Records in the table after addition

OUTPUT-4 Update the Record

https://pythonschoolkvs.wordpress.com/ Page 14

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy