Django Templates
& Forms
Template system, template
tags, Handling forms, model
forms
Program: EDGE-CSE CUET DIGITAL Instructor:
SKILLS TRAINING Tanveer Rahman,
Sr. Software Engineer,
Course: Python (Django) [Intermediate]
Friends Corp.
Lecture: Training Session-09 Chuo-ku, Tokyo, JP
Date: 11th October, 2024
[email protected],
Duration: (2+2) hours 01626735005
Django’s template
system separates
presentation from
business logic.
Allows dynamic
Django
HTML generation
Template using template
s Templates
language. are
typically stored in
the templates
directory within your
app.
Template language uses curly braces {}
and percent signs %.
Template Variable Syntax: {{ variable_name }}
Syntax Template Tags: {% tag_name %} for
logic (loops, conditionals, etc.)
and Tags Example:
Control Structures:
• {% if %}, {% for %},
{% block %}
Common Template Inheritance:
Template • {% extends %}, {% block %},
Tags {% include %}
Filters:
• Modify output of variables, e.g.,
{{ name|upper }}
Task 1: Using Template Tags
and Filters (30 Mins)
• Create a template that displays a list of items from
Book, conditionally rendering messages if the list is
empty.
• Use filters to format dates or text.
Forms in Django
simplify data
collection and
validation.
Support for
Django regular HTML
FORMs forms and Model
Forms.
Built-in validation
and form handling
logic.
Define a form using Django's forms.Form or
forms.ModelForm.
Creating Example:
and
Handling
Forms Handle the form in the view, e.g.,
form.is_valid().
Forms automatically validate data when
submitted.
Form
Custom validation can be added using
clean_fieldname methods or clean.
Validation Example:
Display forms in templates using
{% csrf_token %}
for security.
Template
Use {{ form.as_p }},
and Form {{ form.as_table }}, or
{{ form.as_ul }}
Integratio for layout.
n
Handle form submissions and
redirect upon success.
Task 2: Create a Custom
Form (30 Mins)
• Create a contact form with fields for name, email,
and message.
• Add validation to check that the email domain is
"example.com".
Model Forms automatically
map form fields to model
fields.
Simplifies form creation and
Model validation for database models.
Forms Example:
Reduces redundancy
by using existing
model definitions.
Benefits Automatically
provides field
of Model validation based on
Forms model field types.
Supports CRUD
operations
seamlessly.
Task 3: Create a Model Form
(30 Mins)
• Create a form for a model Book with fields like title,
price, and description etc.
• Implement form validation for price (e.g., must be
positive).
Q&A
Session