0% found this document useful (0 votes)
13 views11 pages

Djangoppt 2

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 PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views11 pages

Djangoppt 2

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 PDF, TXT or read online on Scribd
You are on page 1/ 11

DJANGO TEMPLATES

Django templates are an integral part of the Django framework, providing a


way define the structure of the HTML pages served by your
application. The template system is designed to separate the presentation
logic from the business logic, allowing developers to create dynamic web
pages that change based on the data provided by views.

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.

● File Structure: A template is usually an HTML file that can include


Django Template Language (DTL) syntax to render dynamic content.
For example, 'home.html' might look like this:

<!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

● Django's template language allows you to dynamically insert content,


iterate over data, and implement conditional logic directly within your
HTML templates.

● Variables: Variables are wrapped in double curly braces '{{ }}' and are
replaced with the corresponding values passed from the view.
Example:

<p>Hello, {{ user.username }} ! </p>

● Filters: Filters modify the value of variables. They are applied using
the pipe ‘|’
symbol.
Example:

<p>Current date: {{ current_date l date:”Y-m-d” }}< p>

● 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>

● Comments: Comments are ignored by the template engine and are


useful for leaving notes to the template file.
Example:

{# This is a comment and will not be rendered

3. Template Inheritance Django templates support inheritance, allowing you to


create a base template that defines a common structure (like a header, footer,
and navigation) and extend it in other templates.

● Base Template: A base template might define the overall layout of


your website and include placeholders (blocks) for content that will be
filled in by child templates.
Example:

<!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>&copy; 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 %}

● Template Tags and Custom Tags: Django includes many built-in


template tags for common tasks like including other templates, adding
static files, and handling forms. You can also create custom template
tags to encapsulate complex logic or repeated patterns.

● Static Files: The '{% static %}' tag is used to include static files like
images, CSS, and JavaScript.
Example:
<imgsrc="{% static 'images/logo.png' %}" alt="Logo">

● Template Context: The context is a dictionary of variables that the


view passes to the template. These variables can be displayed in the
template or used to control logic like loops and conditionals.
Example in a view:

from django.shortcuts import render

def home(request):
context = {
'title': 'Home Page',
'message': 'Welcome to my website!',
}
return render(request, 'home.html', context)

● Custom Tags: You can define custom template tags in a Python


module and then use them in your templates to perform specific tasks.
Example:

from django import template

register = template.Library()

@register. simple_tag
def current_year( ) :
import datetime
return date time.date.today().year

Usage In template:

<footer> &copy; {% currentyear %} </footer>

● 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 AND DJANGO FORMS

● Django URLs

Django URLs play a crucial role in routing requests to the appropriate


views in a Django web application. The URL configuration (often referred to as
'URLconf ' ) is how Django knows which piece of code to execute when a user
accesses a particular URL. The URLs are defined in the 'urls.py' file, where you
map URL patterns to view functions or classes
– Basic URL Configuration:

○ 'urls.py' File: Every Django project includes a 'urls.py' file in the


project's main directory. This file is the entry point for URL
configurations and typically includes references to URL patterns
defined in individual apps.
Example of a basic 'urls.py':

from django.contrib import admin


from django.urls import path
from myapp import views

urlpatterns = [
path('admin/‘, admin.site.urls),
path(‘’, views.home, name='home'),
path('about/', views.about, name='about'),
]

○ 'path()' Function: The 'path()' function is used to define a URL


pattern. It takes several arguments:
◆ The route (e.g., "about/"), which is the URL pattern.
◆ The view function or class that handles the request.
◆ An optional 'name' argument, which allows you to refer to this

URL pattern elsewhere in your project.

Example:

path( 'contact/', views.contact, name='contact’)

– Including URLs from Apps:


As a project grows, it is common to break down URL configurations into
multiple files. Each Django app can have its own 'urls.py' file and these can
be included in the main 'urls.py' file of the project.
Including App URLs: Use the 'include()' function to reference URLs from
other apps.
Example:

from django.urls import include


urlpatterns = [
path('blog/‘, include('blog.urls')),
]

In the 'blog' app, the 'urls.py' might look like this:

from django.urls import path


from .import views
urlpatterns = [
path(", views.index, name='index'),
path('post/<int:post_id>/', views.detail, name='detail'),
]

– URL Patterns and Path Converters:

○ Path Converters: Path converters are used to capture URL


parameters and pass them to the view. Django includes several
built-in path converters:
◆ 'str': Matches any non-empty string, excluding the slash (‘/‘)
◆ 'int': Matches an integer.
◆ 'slug': Matches a slug (letters, numbers, underscores, or

hyphens).
◆ 'uuid': Matches a universally unique identifier (UUID).
◆ 'path': Matches a string, including the slash.

Example:

path('post <int:post_id>/‘, views.post_detail, name='post_detail')

○ In this example, 'post_id' is captured from the URL and passed as


an argument to the 'post_detail' view.
○ Named URL Patterns: Giving a URL pattern a name using the
'name' parameter allows you to refer to it in other parts of your
application, such as templates and views.
Example:

path('post/<int:post_id>/', views.post_detail, name.'post_detail')

Usage in a template:

<a href="{% url 'post detail' post_id=1 %}”>View Post</a>

– Regular Expressions in URLs:

○ Django previously used regular expressions to define more


complex URL patterns, but starting with Django 2.0, the 'path()'
function replaced 're_path()'. However, 're_path(). is still available
for cases where more complex pattern matching is required.

Example:

from django.urls import re_path


urlpatterns = [
re_path(r’^post/(?P<slug>[\w-]+)/$’, views.post_detail,
name = ‘post_details’),
]

– Reverse URL Resolution: Django provides a way to reverse the URL


pattern to generate URLs dynamically. The 'reverse()' function and
'reverse_lazy(). function are used to generate URLs from the URL
names defined in 'urls.py'.

Example:

from django.urls import reverse


url = reverse('post_detail', kwargs={‘post_id': 1})

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.

– Creating a Form: Django forms are defined as Python classes that


inherit from 'django.forms.Form' or 'django.forms.ModelForm'. The
class contains form fields that correspond to HTML input elements.

Basic Form Example:

from django import forms

class ContactForm(forms.Form):
name = forms.CharField(max_length=100)
email = forms.EmailField()
message = forms.CharField(widget=forms.Textarea)

○ In this example, 'ContactForm' defines three fields: 'name',


'email', and 'message'. Each field is associated with a specific type
of input (text, email, textarea).

Rendering a Form in a Template:


To display the form in an HTML template, you typically pass it to the
context in a view and use template tags to render the form elements.

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.

– Form Field Types: Django provides a variety of built-in form fields,


each corresponding to a specific type of HTML input. Common form
fields include:
○ 'CharField': Renders as a text input.
○ 'EmailField': Renders as an email input with validation.
○ 'BooleanField': Renders as a checkbox.
○ 'ChoiceField': Renders as a dropdown list.
○ 'DateField': Renders as a date input.
○ 'FileField': Renders as a file upload input.

● Each form field can be customized with additional arguments like


'label', 'initial', 'required', and 'widget'.
Example:

class RegistrationForm(forms.Form):
username = forms.CharField(label=1Username', max_length=100)
password = forms.CharField(widget=forms.PasswordInput)
email = forms.EmailField(label='Email Address')

– Form Validation: Validation ensures that the data submitted by users


meets certain criteria before it is processed. Django forms offer built-
in validation and allow for custom validation methods

Built-in Validation:

○ Fields like ‘EmailField' automatically validate that the input is a


valid email address. If validation fails, an error message is


displayed.

Custom Validation:

○ You can define custom validation logic by adding a


‘clean_<fieldname>()' method in the form class.
Example:

class ContactForm(forms. Form):


name = forms.CharField(max_length=100)
email = forms.EmailField()

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:

○ For validation that depends on multiple fields, override the


'clean()' method.

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:

from django import forms


from .models import Article

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:

Once a ‘ModelForm' is submitted and validated, you can save it


directly to the database using the 'save()' method.

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()

return render(request, ‘create_article.html', {'form': form})

– 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:

class CommentForm(forms .Form) :

comment = forms.CharField(widget=forms.Textarea(attrs={'rows':4, ‘cols’:


40}))

○ Inthis example, the 'Textarea' widget is customized to have 4 rows


and 40 columns.

Custom Widgets:
You can create custom widgets by subclassing 'forms.Widget'.
Example:

from django.forms import Widget

class StarRatingWidget (Widget):

def render(self, name, value, attrs=None, renderer=None) :


return mark_safe(f'<input type="number" name="{name}"
min="1" max="5" value="{value}">')

○ Django Forms provides a robust framework for handling user input,


from simple forms to complex data validation and model
interactions. They ensure that your application remains secure,
organised and easy to maintain.

You might also like