0% found this document useful (0 votes)
9 views

topic-5

Uploaded by

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

topic-5

Uploaded by

vinashreemeshram
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 28

Django

Django is a back-end server side web framework.


Django is free, open source and written in Python.
Django makes it easier to build web pages using Python
How does Django Work?
Django follows the MVT design pattern (Model View Template).
• Model - The data you want to present, usually data from a database.
• View - A request handler that returns the relevant template and content
- based on the request from the user.
• Template - A text file (like an HTML file) containing the layout of the
web page, with logic on how to display the data.
Model

The model provides data from the database.


The most common way to extract data from a database is SQL. One
problem with SQL is that you have to have a pretty good understanding
of the database structure to be able to work with it.
Django, it is easier to communicate with the database, without having
to write complex SQL statements.
The models are usually located in a file called models.py.
View

A view is a function or method that takes http requests as arguments,


imports the relevant model(s), and finds out what data to send to the
template, and returns the final result.

The views are usually located in a file called views.py.


Template

A template is a file where you describe how the result should be


represented.
Templates are often .html files, with HTML code describing the layout
of a web page
Django uses standard HTML to describe the layout, but uses Django
tags to add logic:
<h1>My Homepage</h1>
<p>My name is {{ firstname }}.</p>
The templates of an application is located in a folder named templates.
URLs

Django also provides a way to navigate around the different pages in a


website.
When a user requests a URL, Django decides which view it will send it
to.
This is done in a file called urls.py.
So basically

When you have installed Django and created your first Django web
application, and the browser requests the URL, this is basically what
happens:
1. Django receives the URL, checks the urls.py file, and calls the view
that matches the URL.
2. The view, located in views.py, checks for relevant models.
3. The models are imported from the models.py file.
4. The view then sends the data to a specified template in the
template folder.
5. The template contains HTML and Django tags, and with the data it
returns finished HTML content back to the browser.
My First Project (my_tennis_club)

Django creates a my_tennis_club folder on computer, with this content:


my_tennis_club
manage.py
my_tennis_club/
__init__.py
asgi.py
settings.py
urls.py
wsgi.py
It is important to know that this is the location of your project, and that you can start
building applications in it.
You cannot have a web page created with Django without an app.
But first, let's just create a simple Django app that displays "Hello World!".
Create App
I will name my app members.
Start by navigating to the selected location where you want to store the app, in my case the
my_tennis_club folder, and run .
File structure
y_tennis_club
manage.py
my_tennis_club/
members/
migrations/
__init__.py
__init__.py
admin.py
apps.py
models.py
tests.py
views.py
Views

Django views are Python functions that take http requests and return
http response, like HTML documents.
A web page that uses Django is full of views with different tasks and
missions.
Views are usually put in a file called views.py located on your app's
folder.
There is a views.py in your members folder that looks like this:
Views
my_tennis_club/members/views.py:

from django.shortcuts import render

# Create your views here

from django.shortcuts import render

from django.http import HttpResponse

def members(request):

return HttpResponse("Hello world!")


URLs
Create a file named urls.py in the same folder as the views.py file, and type this code in it :
my_tennis_club/members/urls.py:

from django.urls import path

from . import views

urlpatterns = [ path('members/', views.members, name='members'),]


There is a file called urls.py on the my_tennis_club folder, open
that file and add the include module in the import statement, and
also add a path() function in the urlpatterns[] list

my_tennis_club/my_tennis_club/urls.py:

from django.contrib import admin

from django.urls import include, path

urlpatterns = [

path('', include('members.urls')),

path('admin/', admin.site.urls),

]
Templates
In the Django Intro page, the result should be in HTML, and it should be created
in a template, so
Create a templates folder inside the members folder, and create a HTML file
named myfirst.html.
• <!DOCTYPE html>

• <html>

• <body>

• <h1>Hello World!</h1>

• <p>Welcome to my first Django project!</p>

• </body>

• </html>
Modify the View
Open the views.py file and replace the members view my_tennis_club/members/views.py:

from django.http import HttpResponse


from django.template import loader

def members(request):
template = loader.get_template('myfirst.html')
return HttpResponse(template.render())
Up until now , output has been static data from Python or HTML
templates.
Now we will see how Django allows us to work with data, without
having to change or upload files in the process.
In Django, data is created in objects, called Models, and is actually
tables in a database.
Create Table (Model)
To create a model, navigate to the models.py file in the /members/ folder.
Open it, and add a Member table by creating a Member class, and describe the
table fields in it:

my_tennis_club/members/models.py:

from django.db import models


class Member(models.Model):
firstname = models.CharField(max_length=255)
lastname = models.CharField(max_length=255)
Create Template

• After creating Models, with the fields and data we want in them, it is
time to display the data in a web page.
• Start by creating an HTML file named all_members.html and place it
in the /templates/ folder:
my_tennis_club/members/templates/all_members.html:
<!DOCTYPE html>
<html>
<body>

<h1>Members</h1>

<ul>
{% for x in mymembers %}
<li>{{ x.firstname }} {{ x.lastname }}</li>
{% endfor %}
</ul>

</body>
</html>
Modify View
Next we need to make the model data available in the
template. This is done in the view.
In the view we have to import the Member model, and send it to the template like this:
my_tennis_club/members/views.py:
from django.http import HttpResponse
from django.template import loader
from .models import Member

def members(request):
mymembers = Member.objects.all().values()
template = loader.get_template('all_members.html')
context = {
'mymembers': mymembers,
}
return HttpResponse(template.render(context, request))
Run Example »
The members view does the following:
• Creates a mymembers object with all the values of the Member
model.
• Loads the all_members.html template.
• Creates an object containing the mymembers object.
• Sends the object to the template.
• Outputs the HTML that is rendered by the template.
Details Template
The next step in our web page will be to add a Details page, where
we can list more details about a specific member.

Start by creating a new template called details.html:


my_tennis_club/members/templates/details.html:

<!DOCTYPE html>
<html>
<body>
<h1>{{ mymember.firstname }} {{ mymember.lastname }}</h1>
<p>Phone: {{ mymember.phone }}</p>
<p>Member since: {{ mymember.joined_date }}</p>
<p>Back to <a href="/members">Members</a></p>
</body>
</html>
Add Link in all-members Template
The list in all_members.html should be clickable, and take you to
the details page with the ID of the member you clicked on:

my_tennis_club/members/templates/all_members.html:

<html><body>

<h1>Members</h1>

<ul>

{% for x in mymembers %}

<li><a href="details/{{ x.id }}">{{ x.firstname }} {{ x.lastname }}</a></li>

{% endfor %}

</ul>

• </body></html>
________________________________________
Create new View
Then create a new view in the views.py file, that will deal
with incoming requests to the /details/ url:
my_tennis_club/members/views.py:
from django.http import HttpResponse
from django.template import loader
from .models import Member

def members(request):
mymembers = Member.objects.all().values()
template = loader.get_template('all_members.html')
context = {
'mymembers': mymembers,
}
return HttpResponse(template.render(context, request))
def details(request, id):
mymember = Member.objects.get(id=id)
template = loader.get_template('details.html')
context = {
'mymember': mymember,
}
return HttpResponse(template.render(context, request))
The details view does the following:
• Gets the id as an argument.
• Uses the id to locate the correct record in the Member table.
• loads the details.html template.
• Creates an object containing the member.
• Sends the object to the template.
• Outputs the HTML that is rendered by the template.
Add URLs
Now we need to make sure that the /details/ url points to
the correct view, with id as a parameter.
Open the urls.py file and add the details view to the
urlpatterns list:

my_tennis_club/members/urls.py:
from django.urls import path
from . import views

urlpatterns = [
path('members/', views.members, name='members'),
path('members/details/<int:id>', views.details, name='details'),
]

You might also like