Djangoppt 2
Djangoppt 2
1. Template Files
● File Location: Templates are typically stored in a 'templates/
‘ directory within each project level. Django looks for templates in the
directories specified in the TEMPLATES setting in the setting in
'settings.py.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>{{ title }}</title>
</head>
<body>
<h1>Welcome to {{ title }}</h1>
<p>{{ message }}</p>
</body>
</html>
2. Template Language
● Variables: Variables are wrapped in double curly braces '{{ }}' and are
replaced with the corresponding values passed from the view.
Example:
● Filters: Filters modify the value of variables. They are applied using
the pipe ‘|’
symbol.
Example:
● Tags: Tags provide logic within templates. They are enclosed within
'{% %}' and can be used for loops, conditionals, and more.
Example:
{% if user.is_authenticated %}
<p>Welcome, {{ user.username }}!</p>
{% else %}
<p>Please log in.</p>
{% endif %}
Example of a loop:
<ul>
{% for item in items %}
<li> {{ item.name }} </li>
{% endfor %}
</ul>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8"›
<title>{% block title %} My Site {% endblock %}</title>
</head>
<body>
<header>
<h1>My Website</h1>
<nav>
<ul>
<li> <a href =“/“>Home</a> </li>
<li> <a href =“/about/”> About </a> </li>
</ul>
</nav>
</header>
<main>
{% block content %} {% endblock %}
</main>
<footer>
<p>© 2024 My Website</p>
</footer>
</body>
</html>
● Child Templates: Child templates inherit from the base template and
fill in the defined blocks with specific content.
Example:
{% extends "base.html" %}
{% block title %} Home {% endblock %}
{% block content %}
<h2>Welcome to the Home Page</h2>
<p>This is the home page content.</p>
{% endblock %}
● Static Files: The '{% static %}' tag is used to include static files like
images, CSS, and JavaScript.
Example:
<imgsrc="{% static 'images/logo.png' %}" alt="Logo">
def home(request):
context = {
'title': 'Home Page',
'message': 'Welcome to my website!',
}
return render(request, 'home.html', context)
register = template.Library()
@register. simple_tag
def current_year( ) :
import datetime
return date time.date.today().year
Usage In template:
● Django templates are powerful tools for separating the logic of your
application from its presentation, enabling you to create flexible and
dynamic web pages that enhance user experience.
● Django URLs
urlpatterns = [
path('admin/‘, admin.site.urls),
path(‘’, views.home, name='home'),
path('about/', views.about, name='about'),
]
Example:
hyphens).
◆ 'uuid': Matches a universally unique identifier (UUID).
◆ 'path': Matches a string, including the slash.
Example:
Usage in a template:
Example:
Example:
This will generate a URL based on the named pattern 'post_detail' with
the 'post_id' set to 1.
● Django Forms
Django Forms are a powerful tool for handling user input, rendering HTML
form elements, and validating data in a clean and secure manner. They simplify
the process of creating forms, processing user data, and integrating with
Django models.
class ContactForm(forms.Form):
name = forms.CharField(max_length=100)
email = forms.EmailField()
message = forms.CharField(widget=forms.Textarea)
Example in a view:
from django.shortcuts import render
from .forms import ContactForm
def contact(request):
form = ContactForm()
return render(request, 'contact.html', {'form': form})
Example in a template:
<form method="post">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Submit</button>
</form>
○ The ‘{{ form. as_p }}’ tag renders the form fields as '<p>'
elements. You can also use
' {{ form. as_table }' or '{{ form.as_ul })' to render the form fields differently.
class RegistrationForm(forms.Form):
username = forms.CharField(label=1Username', max_length=100)
password = forms.CharField(widget=forms.PasswordInput)
email = forms.EmailField(label='Email Address')
Built-in Validation:
Custom Validation:
def clean_email(self):
email = self.cleaned_data.get('email')
if not email.endswith('@example.com'):
raise forms.ValidationError('Email must be from example.com
domain. ')
return email
Form-wide Validation:
Example:
class SignupForm(forms.Form) :
Password = forms .CharField(widget=forms .PasswordInput )
confirm_password = forms .CharField(widget=forms .PasswordInput)
def clean(self):
cleaned_data = super().clean()
password = cleaned_data.get('password')
confirm_password = cleaned_data.get(' confirm_password' )
if password != confirm_password:
raise forms.ValidationError('Passwords do not match.")
– Model Forms:
Model forms simplify the process of creating forms that interact with
Django models. A 'ModelForm’ automatically generates form fields based on
the fields of a model.
Creating a ModelForm:
class ArticleForm(forms.ModelForm) :
class Meta:
model = Article
fields = ['title', ‘content’, ‘author']
In this example, ‘ArticleForm’ will generate form fields for the ‘title’,
‘content’, and ‘author’ fields of the ‘Article’ model.
Saving a ModelForm:
Example:
def create_article(request):
if request.method == ‘POST':
form = ArticleForm(request.POST)
if form.is_valid():
form.save()
return redirect( ‘article list’)
else:
form = ArticleForm()
– Form Widgets:
Widgets are responsible for rendering the HTML input elements in forms.
Django provides a variety of built-in widgets, and you can customize or create
your own.
Customizing Widgets:
Example:
Custom Widgets:
You can create custom widgets by subclassing 'forms.Widget'.
Example: