Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
14 views41 pages

Template

Django templates separate the presentation layer from business logic, allowing for dynamic web pages using Django Template Language (DTL). Templates use variables, filters, and tags for content rendering and can be organized through template inheritance for reusability. The document also includes practical examples and exercises for creating and rendering templates in Django applications.

Uploaded by

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

Template

Django templates separate the presentation layer from business logic, allowing for dynamic web pages using Django Template Language (DTL). Templates use variables, filters, and tags for content rendering and can be organized through template inheritance for reusability. The document also includes practical examples and exercises for creating and rendering templates in Django applications.

Uploaded by

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

Templates in Django

Understanding Templates, DTL, and


Rendering
Templates
• In Django, templates are used to separate the
presentation layer (HTML/CSS) from the
business logic (Python code in
views/models). This follows the MVC/MVT
architecture, where:
M (Model): Manages data.
V (View): Handles logic.
T (Template): Handles the presentation
What is a Template?
• A template is an HTML file with Django code.
• Used to create dynamic web pages.
• Example: <h1>Welcome {{ name }}</h1>
Why use Templates?
• Separates Presentation (HTML) from Logic
(Python).
• Easy to reuse across project.
• Helps in creating dynamic content from
database.
Creating Templates
• Steps:
• Create 'templates' folder inside your app.
student/templates/home.html
• Write HTML code inside home.html
• Example: <h1>Hello Django!</h1>
Django Template Language (DTL)
Supports Variables, Filters and Tags.
Variables: {{ user }} #to display content from the
view context.
Filters: {{ name|upper }}#Filters modify data
before display
Tags: {% if user.is_authenticated %} ... {% endif
%}#Used for logic and loops
For loop
<ul>
{% for fruit in fruits %}
<li>{{ fruit }}</li>
{% endfor %}
</ul>
If-else
{% if fruits %}
<p>We have fruits.</p>
{% else %}
<p>No fruits available.</p>
{% endif %}
Comment
{% comment %}
This is a template comment
{% endcomment %}
Rendering Templates
In views.py:
from django.shortcuts import render

def home(request):
return render(request, 'student/home.html',
{'user': 'xyz'})
Summary
• Templates = HTML + DTL
• Makes webpages dynamic & reusable
• Use {{ }} for variables
• Use {% %} for logic
HTML File
<!DOCTYPE html>
<html>
<head>
<title>Fruit List</title>
</head>
<body>
<h1>My Favorite Fruits</h1>
<ul>
{% for fruit in fruits %}
<li>{{ fruit }}</li>
{% endfor %}
</ul>
</body>
</html>
Render in Views.py
from django.shortcuts import render

def fruit_list(request):
fruits = ["Apple", "Banana", "Mango",
"Orange"]
return render(request, "myapp/fruits.html",
{"fruits": fruits})
Mapping to URL
from django.urls import path
from . import views

urlpatterns = [
path("fruits/", views.fruit_list,
name="fruit_list"),
]
• Display a variable
In your template, display a variable school_name
passed from the view.
Use a filter to convert it to uppercase.
• Loop through a list
Pass a list of subjects ['Math', 'Science', 'English'] from
the view.
Display them in an unordered list (<ul>).
Practice Questions
1.Display a GreetingPass a variable name = “XYZ" from the
view.Display: Hello, {{ name }}! in the template.

2.Show Today's DatePass the current date from the


view.Display it in the template using the date filter in the
format D M Y.

3.Conditional MessagePass is_holiday = True from the


view.Show “Enjoy your holiday!” if True, else “Back to work.”

4.Uppercase and LowercasePass city = 'Delhi'.Display it in


uppercase and lowercase using filters.
Template Inheritance

• Create base templates that can be extended


by child templates
• Django template inheritance using a
restaurant menu example
• Template inheritance in Django works like a
restaurant menu system:
• You create a base template (like a menu
layout)
• You create child templates that fill in the
specific content for each day
• All menus share the same overall design but
have different dishes
Base Template (Restaurant Layout) -
base.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>{% block title %}Ram Restaurant{% endblock %}</title>
<style>
body { font-family: 'Segoe UI', sans-serif; margin: 0; padding: 0; }
.header { background: #d32f2f; color: white; padding: 15px; text-align: center; }
.footer { background: #333; color: white; padding: 10px; text-align: center; margin-top: 20px;
}
.content { padding: 20px; }
.menu-item { border: 1px solid #ddd; margin: 10px 0; padding: 15px; border-radius: 5px; }
</style>
</head>
<body>
<div class="header">
<h1>Ram Restaurant</h1>
<p>Traditional Delicious Food</p>
</div>

<div class="content">
{% block content %}
<!-- Different menu content will go here -->
{% endblock %}
</div>

<div class="footer">
<p>Contact: 1234, Main Street, City | Phone: 0123-456789</p>
<p>© 2023 Ram Restaurant. All rights reserved.</p>
</div>
</body>
</html>
monday_menu.html
{% extends "base.html" %}

{% block title %}Monday Menu - Ram Restaurant{% endblock %}

{% block content %}

<h2>Monday Special Menu</h2>

<p>Every Monday 10% discount on all dishes</p>


<div class="menu-item">
<h3>Vegetarian Thali</h3>
<p>…………...</p>
</div>
<div class="menu-item">
<h3>……………..r</h3>
<p>………………………….</p>

</div>
{% endblock %}
tuesday_menu.html
{% extends "base.html" %}
{% block title %}Tuesday Menu - Ram
Restaurant{% endblock %}
{% block content %}
<h2>Tuesday Special Menu</h2>
<p>……………………………</p>
<div class="menu-item">
<h3>……………….</h3>
<p>………………</p>
</div>
<div class="menu-item">
<h3>…………….</h3>
<p>…………</p>
</div> {% endblock %}
• {% extends "base.html" %} - Tells Django this
template extends base.html
• {% block content %} - Defines what content to
place in the base template's content block
• {% endblock %} - Marks the end of the block
Views.py
from django.shortcuts import render

def monday_menu(request):
return render(request, 'monday_menu.html')

def tuesday_menu(request):
return render(request, 'tuesday_menu.html')
urls.py
from django.urls import path
from . import views

urlpatterns = [
path('monday/', views.monday_menu,
name='monday_menu'),
path('tuesday/', views.tuesday_menu,
name='tuesday_menu'),
]
Questions
• Basic Template Variables
Create a view that passes a user's name, age, and
favorite color to a template
Display these values in an HTML page with
appropriate formatting
Questions
• Conditional Statements
Create a template that displays different messages
based on:
• Whether a user is authenticated or not
• The time of day (morning, afternoon, evening)
• A product's stock status (in stock, low stock, out of
stock)
Questions
• Loop Practice
Create a list of products with names, prices, and
categories
Display them in a table with alternating row colors
Add a "Sale" badge for products with prices below
$20
Questions
• Template Inheritance
Create a base template with a header, navigation,
content area, and footer
Extend this base template for:
• A home page with a welcome message
• A products page listing items
• A contact form page
Questions
• URL Tag Practice
• Create a navigation menu that uses
the{%url%} tag for all links

Create a product detail page that links to related


products using URL tags
Questions
• Filter Usage
Format dates in different ways throughout your
templates
Truncate long text descriptions to 50 characters with
an ellipsis
Convert text to uppercase for headings and title
case for product names
Dynamic Templates in Django
• Templates in Django allow you to dynamically
generate HTML content using variables and
logic.
Dynamic Templates in Django
Templates use Django Template Language (DTL).
Variables passed from views can be displayed.
Tags and filters allow dynamic formatting.
Views.py
from django.shortcuts import render
from datetime import date

def home(request):
context = {
"name": "Swarnima",
"today": date.today(),
"fruits": ["Apple", "Banana", "Mango"]
}
return render(request, "home.html", context)
home.html
<h1>Hello, {{ name }}!</h1>
<p>Today is: {{ today|date:"D d M Y" }}</p>

<h3>My Fruits:</h3>
<ul>
{% for fruit in fruits %}
<li>{{ fruit }}</li>
{% endfor %}
</ul>
Debugging Django Applications
• When errors occur, Django provides detailed
error pages in DEBUG mode.
DEBUG = True in settings.py (for developmentonly).
Use print() in views or logging for tracking values.
Django Debug Toolbar (install separately).
Common issues:
Template not found → check TEMPLATES in
settings.py.
Wrong context variable → check dictionary keys.
URL routing error → confirm urls.py.
Questions
1.Write a Django view that sends a list of cities
(["Delhi", "Mumbai", "Chennai"]) to a template.
Display them in an unordered list using a {% for %}
loop.
2.Use template filters to:
Show today’s date in format Monday, 1 September
2025.
Convert a name “xyz" into Title case (XYZ).
3.Display student marks dynamically and highlight
marks above 90 in green and below 50 in red using
{% if %} conditions.
Questions
4.Create a base.html with a navbar and footer. Then
make:
about.html page that extends base and displays "About
Our Company".
contact.html page that extends base and shows an email
form.
5.In a project, you want all pages to share the same CSS
file. Where should you include the <link rel="stylesheet">
tag — in base.html or in child.html? Why?
6.Modify a base.html with a block called sidebar. Show
different sidebars in two child templates (Blog Page and
Shop Page).

You might also like