unit 5 - Django Template Language.docx
unit 5 - Django Template Language.docx
Django's template system is one of its key features, designed to separate the logic of the
application (views) from its presentation (HTML). The Django Template Language (DTL)
provides tools for rendering dynamic web pages by combining static HTML and dynamic
content. DTL is a powerful templating system used in Django to dynamically generate
HTML. It separates the logic from the presentation, making your web applications more
maintainable and scalable. It allows developers to create dynamic web pages by embedding
variables, control structures, and other elements in HTML templates.
Key Features of DTL:
● Separation of Concerns: Template language helps to separate the presentation layer
from the business logic layer.
● Readable and Simple: DTL syntax is simple and easy to read, focusing on markup
rather than complex logic.
Key Components of Django Template Language:
1. Variables:
Variables are used to dynamically display data from the view in templates.
Syntax: {{ variable_name }}
Example: {{ user.username }} displays the username of the logged-in user.
2. Tags:
Tags are enclosed in {% %} and are used to perform logic operations such as loops,
conditionals, and template inclusions.
Common tags include:
{% if %}, {% for %}: Conditional and loop control structures.
{% include %}, {% extends %}: Template inheritance and inclusion.
{% block %}, {% endblock %}: Define content blocks for inheritance.
Example:
▪ {% if user.is_authenticated %}
▪ <p>Welcome back, {{ user.username }}!</p>
▪ {% endif %}
3. Filters:
Filters modify the value of a variable before displaying it in the template.
Syntax: {{ variable|filter_name }}
Common filters: date, length, lower, default, etc.
Example: {{ name|lower }} converts the name to lowercase.
4. Template Inheritance:
Allows for a common structure (like headers, footers) to be reused across multiple
templates, reducing redundancy.
The base template defines blocks (e.g., {% block content %}) that child templates can
override.
Example:
o Base template (base.html):
<html>
<head><title>{% block title %}My Site{% endblock
%}</title></head>
<body>{% block content %}{% endblock %}</body>
</html>
o Child template (home.html):
{% extends 'base.html' %}
{% block title %}Home Page{% endblock %}
{% block content %}
<h1>Welcome to the Home Page</h1>
{% endblock %}
5. Rendering Templates:
Templates are rendered in Django views using the render() function, which takes the
request, template name, and context (data to pass to the template).
Example:
from django.shortcuts import render
def home(request):
context = {'title': 'Welcome'}
return render(request, 'home.html', context)
6. Form Handling:
Django simplifies form creation and rendering. Form data is passed to templates using
context, and errors are automatically displayed if validation fails.
Example:
<form method="POST">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Submit</button>
</form>
Filters: Filters modify variables to produce different output. They are applied after
variables and are enclosed in pipe characters |. Common filters include:
o default: Provides a default value if the variable is empty
o date: Formats dates and times
o lower, upper: Converts text to lowercase or uppercase
o truncatechars: Truncates text to a specified number of characters
Example:
<p>The current date is {{ today_date|date:"Y-m-d" }}</p>
<p>{{ name|lower }}</p>
Rendering Templates
To render a template, Django’s render() function is used in views. This function takes three
arguments:
1. Request object: The HTTP request.
2. Template name: The HTML file to be rendered.
3. Context: A dictionary containing dynamic data to pass to the template.
Example:
from django.shortcuts import render
def home(request):
context = {'greeting': 'Hello, World!'}
return render(request, 'home.html', context)
Template Inheritance
Template inheritance allows you to create a base template with common elements (such as a
header, footer, or navigation bar) that can be reused across other templates. This helps avoid
redundancy and makes maintaining the application easier. Template inheritance allows you to
create reusable base templates and extend them to create more specific templates. Template
Inheritance in Django is a powerful feature that allows you to create a base template with
common structure and elements (like headers, footers, or navigation bars) and reuse it across
multiple templates. This reduces redundancy and makes your project more maintainable. In
Django, template inheritance works by using {% extends %} to inherit a base template and
{% block %} to define sections of the template that can be overridden by child templates.
{% extends 'base.html' %}
{% block title %}Home Page{% endblock %}
{% block header %}Home Page Header{% endblock %}
{% block content %}
<p>Welcome to the home page!</p>
{% endblock %}
Form Handling
In Django, forms are used to capture and process user input. Django forms can be rendered
dynamically, and the form’s fields can be validated automatically. Django provides a
powerful form handling framework that simplifies the process of creating, validating, and
processing forms.
Example:
1. Form Class:
from django import forms
class ContactForm(forms.Form):
name = forms.CharField(max_length=100)
email = forms.EmailField()
message = forms.CharField(widget=forms.Textarea)
2. View:
from django.shortcuts import render
from .forms import ContactForm
def contact(request):
form = ContactForm()
if request.method == 'POST':
form = ContactForm(request.POST)
if form.is_valid():
# Process form data
name = form.cleaned_data['name']
email = form.cleaned_data['email']
message = form.cleaned_data['message']
# Return a response (or redirect)
return render(request, 'contact.html', {'form': form})
3. Template (contact.html):
<form method="POST">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Submit</button>
</form>
# forms.py
from django import forms
from django.core.exceptions import ValidationError
class ContactForm(forms.Form):
name = forms.CharField(max_length=100, required=True, label='Your Name')
email = forms.EmailField(required=True, label='Your Email')
message = forms.CharField(widget=forms.Textarea, required=True, label='Your Message')
def contact_view(request):
if request.method == 'POST':
form = ContactForm(request.POST)
if form.is_valid():
# Process the data
name = form.cleaned_data['name']
email = form.cleaned_data['email']
message = form.cleaned_data['message']
# In a real scenario, you would save this to the database or send an email
return render(request, 'contact_success.html', {'name': name})
else:
# If the form is invalid, it will contain errors
return render(request, 'contact_form.html', {'form': form})
else:
form = ContactForm()
return render(request, 'contact_form.html', {'form': form})
{% if form.errors %}
<ul>
{% for field, errors in form.errors.items %}
<li>{{ field }}:
<ul>
{% for error in errors %}
<li>{{ error }}</li>
{% endfor %}
</ul>
</li>
{% endfor %}
</ul>
{% endif %}
Explanation of Template:
● {{ form.as_p }}: This renders the form fields as paragraphs. Django automatically
displays error messages next to the corresponding fields when they are invalid.
● Displaying Errors: If there are any errors (form.errors), they are displayed in an
unordered list. Each field's errors are listed under the field name
Form Display
To display a form in the template, you can use Django’s built-in methods like {{ form.as_p
}}, {{ form.as_table }}, or {{ form.as_ul }}. Each of these methods renders the form fields in
different formats. Django's form rendering system generates HTML forms based on the form
fields defined in your form class. You can customize the appearance of forms using template
tags and filters.
class ContactForm(forms.Form):
name = forms.CharField(max_length=100)
email = forms.EmailField()
message = forms.CharField(widget=forms.Textarea)
def contact_view(request):
form = ContactForm()
return render(request, 'contact_form.html', {'form': form})
To develop a webpage explaining Django CRUD (Create, Read, Update, Delete) functions
using Class-Based Views (CBVs), we'll walk through the process of setting up a simple
Django app with class-based views for each of the CRUD operations.
Step-by-Step Guide
1. Create a New Django Project and App
First, make sure you have Django installed. If you don’t, you can install it using pip:
pip install django
Now, create a new Django project and an app where we'll build our CRUD functionality.
# Create a new project
django-admin startproject crud_project
class Book(models.Model):
title = models.CharField(max_length=100)
author = models.CharField(max_length=100)
published_date = models.DateField()
def __str__(self):
return self.title
After defining the model, run the migrations to create the database schema:
# Create migration files
python manage.py makemigrations
4. Set Up URLs
In crud_app/urls.py, create URL patterns that map to the views we created.
crud_app/urls.py
from django.urls import path
from .views import BookListView, BookDetailView, BookCreateView,
BookUpdateView, BookDeleteView
urlpatterns = [
path('books/', BookListView.as_view(), name='book_list'),
path('book/<int:pk>/', BookDetailView.as_view(), name='book_detail'),
path('book/new/', BookCreateView.as_view(), name='book_create'),
path('book/<int:pk>/edit/', BookUpdateView.as_view(), name='book_edit'),
path('book/<int:pk>/delete/', BookDeleteView.as_view(), name='book_delete'),
]
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('crud_app.urls')), # Include the URLs from the CRUD app
]
6. Create Templates
Now, let’s create HTML templates for the views. All templates will be stored in the templates
folder of crud_app.
crud_app/templates/book_list.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Books</title>
</head>
<body>
<h1>Book List</h1>
<a href="{% url 'book_create' %}">Add a new book</a>
<ul>
{% for book in books %}
<li>
<a href="{% url 'book_detail' book.pk %}">{{ book.title }}</a>
<a href="{% url 'book_edit' book.pk %}">Edit</a>
<a href="{% url 'book_delete' book.pk %}">Delete</a>
</li>
{% endfor %}
</ul>
</body>
</html>
crud_app/templates/book_detail.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>{{ book.title }}</title>
</head>
<body>
<h1>{{ book.title }}</h1>
<p>Author: {{ book.author }}</p>
<p>Published Date: {{ book.published_date }}</p>
<a href="{% url 'book_edit' book.pk %}">Edit</a>
<a href="{% url 'book_delete' book.pk %}">Delete</a>
<a href="{% url 'book_list' %}">Back to Book List</a>
</body>
</html>
crud_app/templates/book_form.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>{{ view.title }}</title>
</head>
<body>
<h1>{{ view.title }}</h1>
<form method="post">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Submit</button>
</form>
<a href="{% url 'book_list' %}">Back to Book List</a>
</body>
</html>
crud_app/templates/book_confirm_delete.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Confirm Delete</title>
</head>
<body>
<h1>Are you sure you want to delete this book?</h1>
<p>{{ book.title }} by {{ book.author }}</p>
<form method="post">
{% csrf_token %}
<button type="submit">Yes, delete it</button>
</form>
<a href="{% url 'book_list' %}">Cancel</a>
</body>
</html>
7. Admin Panel (Optional)
To easily add, update, or delete books, you can register the Book model in the Django
admin.
crud_app/admin.py
admin.site.register(Book)
8. Run the Server
Now that everything is set up, you can run the server:
python manage.py runserver
9. Visit the Web Pages
● Create a Book: Visit /book/new/ to add a new book.
● List Books: Visit /books/ to view the list of books.
● View Book Details: Click on a book title in the list to view its details.
● Edit Book: Click on the "Edit" link next to a book to update it.
● Delete Book: Click on the "Delete" link next to a book to delete it.