KEMBAR78
Unit-1 Pythone Framework | PDF | Databases | Model–View–Controller
0% found this document useful (0 votes)
11 views29 pages

Unit-1 Pythone Framework

The document provides an overview of the Django framework, detailing its design principles, architecture, installation methods, and the creation of projects and applications. It emphasizes Django's focus on reusability, modularity, and clarity in web development, while also outlining the roles of URLs, templates, and apps in the framework. Additionally, it includes practical instructions for setting up a Django project and configuring its components.

Uploaded by

Shaad Tanwar
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)
11 views29 pages

Unit-1 Pythone Framework

The document provides an overview of the Django framework, detailing its design principles, architecture, installation methods, and the creation of projects and applications. It emphasizes Django's focus on reusability, modularity, and clarity in web development, while also outlining the roles of URLs, templates, and apps in the framework. Additionally, it includes practical instructions for setting up a Django project and configuring its components.

Uploaded by

Shaad Tanwar
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/ 29

Python Framework

Programme Master of Science (Information Technology)

Semester II

Course Code 101410236

Course Title Python Framework

Unit-1

Introduction – Django Framework

Introduction – Django Framework: Design principles, Introduction - URLs,

Templates, Apps, Understand setup of Django admin site App

Django – URLs and Views: URL – Regular expressions, Parameters and Query

strings, Consolidation and Modularization, Naming and Namespace Views –

Method requests and response, Method middleware, Flash messages, Classbased

views

Django – Templates: Syntax, Configuration, Reusable template, Built-in context

processors, Custom context processors, Built-in Filters and Tags, Custom filters
Python Framework

What is django?
• Django is a Python framework that makes it easier to create web sites using
Python.

• Django takes care of the difficult stuff so that you can concentrate on building
your web applications.

• Django emphasizes reusability of components, also referred to as DRY (Don't


Repeat Yourself), and comes with ready-to-use features like login system,
database connection and CRUD operations (Create Read Update Delete).

• Django is especially helpful for database driven websites.

• Django official Website: https://www.djangoproject.com/

History of the Django Framework

• The Django framework started in 2003, as a project done by Adrian Holovaty and
Simon Willison at the Journal-World newspaper in Lawrence, Kansas, in the
United States.

• In 2005, Holovaty and Willison released the first public version of the
framework, naming it after the Belgian-French guitarist Django Reinhardt.

• the Django framework now operates under the guidance of the Django Software
Foundation (DSF), the framework core has over 1000 contributors with more
than 15 release versions

• there are over 3000 packages specifically designed to work with the Django
framework.
Python Framework

Django’s architecture
• The Django framework has remained true to its origins as a Model-View-
Controller (MVC) server-side framework designed to operate with relational
databases.

• Once you install the Django framework, you’ll learn how to start a Django project
and how to set it up with a relational database.

• Next, you’ll learn about the core building blocks in the Django framework – urls,
templates, and apps – and how they work with one another to set up content.

• The Model-View-Template also known as MVT architecture is used by Django. It


is a software design pattern for developing a web application. The Django MVT
Structure is made up of three parts:

• The model will serve as an interface for your data. It is in charge of data
management. A database represents the logical data structure that supports the
entire application such as MySql and Postgres.

• The View is the user interface, that renders a website page in your browser.
HTML/CSS/Javascript and Jinja files are used to represent it.

• A template is made up of both static sections of the desired HTML output and
specific syntax that describes how dynamic content will be included.
Python Framework

Django Framework Design Principles

If you work long enough in web development, you’ll eventually come to the conclusion
that you can produce the same results with just about any web framework and
programming language.

The Django framework uses a set of design principles that produces one of the most
productive web development processes compared to many other web frameworks.

I. Don’t Repeat Yourself (DRY) Principle

II. Explicit Is Better Than Implicit

III. Loosely Coupled Architecture

Don’t Repeat Yourself (DRY) Principle

Repetition might be good to emphasize a point, but when it comes to web development,
it just leads to additional and time-consuming work.

Django approach encourages creating reusable components, which leads to a modular


codebase where each piece of functionality is defined once and then referenced or used
throughout the project. Here's how Django fosters DRY principles:

1. Modular Structure: Django encourages breaking down a project into smaller,


reusable applications (or apps), each handling a specific function or domain.
These apps can be easily reused across different projects, promoting code reuse
at the project level.
2. Template System: Django’s templating system allows developers to create
reusable templates and use template inheritance, where a base template defines
a common structure (like headers, footers, and navigation bars). Other templates
extend this base, adding only what’s unique. This minimizes repeated HTML code
and makes it easy to update layouts.
3. ORM (Object-Relational Mapping): Django's ORM lets you define database
models once, and it handles much of the CRUD operations (Create, Read, Update,
Delete) automatically. This eliminates repetitive SQL queries across the
codebase.
4. Form Handling: Django has built-in forms that handle form rendering,
validation, and processing in a structured way, reducing the need to write
repetitive form-related code.
5. Django Middleware: Middleware allows developers to define reusable
components for handling requests and responses. Common functions like
authentication, session management, and error handling can be handled by
middleware and reused across views.
Python Framework

Explicit Is Better Than Implicit

The idea that "Explicit is better than implicit" is a key part of Django’s design
philosophy,

which is inspired by the Zen of Python, a collection of guiding principles for writing
computer programs in Python.

In Django, this principle promotes clarity and readability, aiming to make it obvious
what the code does without requiring developers to guess.

Here are some examples of how Django applies this principle:

1. URL Routing

 Django requires explicit URL routing in urls.py. This means that every URL path
is mapped to a specific view function, making it clear what URLs are available
and what functionality they trigger.
 Rather than automatically guessing URLs based on views or models, Django's
approach ensures that you define each route explicitly.

2. Settings Configuration

 Django’s configuration settings are highly explicit. Settings like DATABASES,


INSTALLED_APPS, TEMPLATES, and more are configured directly in settings.py.
This approach makes it very clear what environment or database connections
are used without requiring implicit behavior.

3. Database Migrations

 In Django, you create explicit migrations to change the database schema. This
requires you to write or generate migration files for each change, making the
database’s evolution transparent and reducing unexpected behavior.

4. Form and Model Definitions

 Django’s ORM (Object-Relational Mapper) requires models and forms to be


defined explicitly. Each field on a model or form is specified in the code, making
it clear what data is expected and reducing any ambiguity.

5. Template Rendering

 Template rendering in Django is explicit as well, with variables passed directly


into the template context. Instead of having global variables or magical objects
available, you define exactly what data the template has access to.
Python Framework

Loosely Coupled Architecture


Django’s loosely coupled architecture is another important design principle that aligns
with the goal of creating a modular, flexible, and reusable framework.

Loosely coupled architecture means that different components of Django can work
independently without too much dependency on each other.

Here’s how Django applies this principle and why it’s beneficial

1. Applications as Modules

 In Django, projects are organized into “apps,” which are essentially smaller
components that can be developed, tested, and maintained independently.
 Apps can be reused across multiple projects, and since they’re self-contained,
you can easily plug them in or remove them as needed.

2. Middleware Components

 Middleware in Django acts as a modular layer between requests and views. Each
middleware component is independent and serves a specific purpose, like
handling security, session management, or authentication.
 This independence allows developers to add, remove, or customize middleware
without affecting the overall application.

3. URL Routing

 URL routing is separated from the view logic in Django. By using urls.py, you can
define your URL structure independently from the view functions that handle
them.
 This approach allows you to change URLs or add new ones without modifying
the actual view code, making updates simpler and more organized.

4. Template System

 Django’s templating engine is separate from the application logic. This allows for
easy separation of front-end and back-end code, so designers and developers can
work independently.
 You can use Django's templating language or swap it out for another engine if
needed, thanks to this loose coupling.

5. ORM (Object-Relational Mapping) Layer

 The ORM in Django is abstracted, so it’s loosely coupled with the database back-
end. This means you can switch databases (e.g., from SQLite to PostgreSQL) with
minimal changes to your code.
 The ORM makes database queries in a standardized way, allowing you to interact
with the database without writing SQL.
Python Framework

6. Signals

 Signals allow different parts of Django to communicate when certain events


occur, such as saving a model. They enable decoupling by allowing code to
“listen” for events without directly modifying other code.
 Signals make it possible to perform actions when specific events happen (like
sending a welcome email upon user registration) without changing the core app
logic.

Installation of Django and SQL Package

Approach Pros Cons

Download/install with Allows install on virtual Latest version may not be


pip Python package Python environment. available.
manager. (Recommended Dependencies are taken
option) care of automatically.
Download from main site Easiest access to latest Requires manual download
as tar.gz file. Django stable release. and install. Requires
additional management of
Django dependencies (if not
using pip).
Download from Git Access to the latest Django Can contain bugs. Requires
features. additional management of
Django dependencies (if not
using pip).
Download/install from Easy to install. Latest version may not be
OS package manager Dependencies are taken available. Installed on
(apt-get) care of automatically. global Python environment.

Install Django with pip


Syntax

pip install Django


Python Framework

Install Python Database Packages

Besides configuring Django to connect to a database, you’ll also need to install the
necessary Python packages to communicate with your database brand

Database Python Package pip installation syntax


PostgreSQL psycopg2 pip install psycopg2
MySQL mysql-python pip install mysql-python
Oracle cx_Oracle pip install cx_Oracle
SQLite Included with Python 2.5+ N/A
MSSQL mssql pip install mssql

Example

Start a Django Project and application (app)

To start a Django project you must use the django-admin executable or django-admin.py
script that comes with Django.

After you install Django, both this executable and script should be accessible from any
directory on your system (e.g., installed under /usr/bin/,/usr/local/bin/ or the /bin/
directory of a virtualenv).

Syntax(create a project)

#Create a project called coffeehouse


Python Framework

django-admin startproject coffeehouse

#Create a project called sportstats

django-admin startproject sportstats

 manage.py: A command-line utility that lets you interact with this Django
project in various ways. You can read all the details about manage.py in django-
admin and manage.py.

 coffeehouse/: A directory that is the actual Python package for your project. Its
name is the Python package name you’ll need to use to import anything inside it
(e.g. mysite.urls).

 __init__.py: An empty file that tells Python that this directory should be
considered a Python package. If you’re a Python beginner, read more about
packages in the official Python docs.

 settings.py: Settings/configuration for this Django project. Django settings will


tell you all about how settings work.

 urls.py: The URL declarations for this Django project; a “table of contents” of
your Django-powered site. You can read more about URLs in URL dispatcher.

 asgi.py: An entry-point for ASGI-compatible web servers to serve your project.


See How to deploy with ASGI for more details.

 wsgi.py: An entry-point for WSGI-compatible web servers to serve your project.


See How to deploy with WSGI for more details.
Python Framework

Understand Urls, Templates, and Apps

Content in Django projects works with three major building blocks: urls, templates, and
apps.

You create and configure Django urls, templates, and apps separately, though you
connect one to another to fulfill content delivery,

which is part of Django’s loosely coupled architecture design principles.

As you can see in Figure, there are two separate pipelines to deliver either static or
dynamic content. More importantly, notice how each of the different Django layers is
loosely coupled

Create and Configure Django Urls

The main entry point for Django urls is the urls.py file created when you start a project -
if you’re unfamiliar with a Django project structure,

If you open the urls.py file, you’ll notice it only has one active url to /admin/ that is the
Django admin
Python Framework

Now that you’re familiar with the urls.py file syntax, let’s activate a url to view custom
content on the home page of a Django project.

Example (urls.py)

from django.conf.urls import url from django.contrib import admin

from django.views.generic import TemplateView

urlpatterns = [ url(r'^admin/', admin.site.urls),


url(r'^$',TemplateView.as_view(template_name='homepage.html')), ]

Create and Configure Django Templates


By default, Django templates are interpreted as HTML.

First we have to create directory or folder Templates under Project for example

This means Django templates are expected to have a standard HTML document
structure and HTML tags under Templates folder

Example- Template homepage.html

<html>

<body>

<h4>Home page for Django</h4>

</body>

</html>

Once you have a directory with Django templates, you need to configure a Django
project so it can find the templates in this directory. In the settings.py file of the Django
project
Python Framework

Example:- TEMPLATES and DIRS definition in settings.py

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

PROJECT_DIR = os.path.dirname(os.path.abspath(__file__))

TEMPLATES = [ {

'BACKEND': 'django.template.backends.django.DjangoTemplates',

'DIRS': ['%s/templates/' % (PROJECT_DIR),],

'APP_DIRS': True,

'OPTIONS': { 'context_processors': [

'django.template.context_processors.debug',

'django.template.context_processors.request',

'django.contrib.auth.context_processors.auth',

'django.contrib.messages.context_processors.messages',

], },

}, ]

output
Python Framework

Create and Configure Django Apps


Django apps are used to group application functionality. If you want to work with
content from a database or user interactions you have to create and configure Django
apps.

A project can contain as many apps as you need.

For example,

if you have a project for a coffeehouse, you can create an app for stores, another app for
menu items, another app for about information, and create additional apps as they’re
needed.

You may not have realized it, but in the previous section when you set up a database for
a django project, you already worked with django apps when you invoked the migrate
operation.

Syntax (create a App)

Steps to create app

1. cd <project_name>(coffeehouse)
2. #Create a app called coffee(app)
django-admin startapp coffee
Python Framework

A subdirectory named about is created containing the app. By default, upon creating an
app its subdirectory includes the following:

 __init__.py .- Python file to allow app packages to be imported from other


directories.
Note __init__.py is not a Django specific file, it’s a generic file used in almost all
Python applications.
 migrations.- Directory that contains migrations applied to the app’s database
definitions (i.e., model classes)
 admin.py .- File with admin definitions for the app - such definitions are needed
to access model class instances from the Django admin.
 apps.py .- File with configuration parameters for the app.
 models.py .- File with database definitions (i.e., model classes) for the app.
 tests.py .- File with test definitions for the app.
 views.py .- File with view definitions (i.e., controller methods) for the app.

Example:-Add app to INSTALLED_APPS in Django settings.py

INSTALLED_APPS = [

'django.contrib.admin',

'django.contrib.auth',

'django.contrib.contenttypes',

'django.contrib.sessions',

'django.contrib.messages',

'django.contrib.staticfiles',

'coffeehouse.about',

By default, INSTALLED_APPS contains the above apps, all of which come with Django:

 django.contrib.admin – The admin site. You’ll use it shortly.

 django.contrib.auth – An authentication system.

 django.contrib.contenttypes – A framework for content types.

 django.contrib.sessions – A session framework.

 django.contrib.messages – A messaging framework.

 django.contrib.staticfiles – A framework for managing static files.


Python Framework

Set Up the Django admin Site

The Django admin site provides a web-based interface to access the database connected
to a Django project.

Even for experienced technical administrators, doing database CRUD (Create-Read-


Update-Delete) operations directly on a database can be difficult and time consuming,

given the need to issue raw SQL commands and navigate database structures

Step-1 open a Django project’s urls. py file, in the urlpatterns variable you’ll see the line

url(r'^admin/', admin.site.urls).

Step-2 if you open the project’s settings.py file and go to the INSTALLED_APPS variable,
near the top of this variable you’ll see the line django.contrib.admin that indicates the
Django admin site app is enabled.

Step-3 Start the development web server by executing python manage.py runserver

Step-4 Open a browser on the Django admin site http://127.0.0.1:8000/admin/.


Python Framework

Step-5 Next, let’s create a Django superuser or administrator to access the Django
admin via the interface in

Create Django superuser for admin interface

[user@coffeehouse ~]$ python manage.py createsuperuser

Username (leave blank to use 'admin'):

Email address: admin@coffeehouse.com

Password:

Password (again):

The password is too similar to the email address.

This password is too short. It must contain at least 8 characters.

This password is too common.

Password:

Password (again):

Superuser created successfully

Django Urls and Views

Regular Expressions in Django

Regular expressions (regex) are powerful pattern-matching tools used extensively in


Django for URL routing and validation.

Basic Regex URL Patterns

URL.PY

from django.urls import re_path


from django.views import View

urlpatterns = [
# Match a numeric ID
re_path(r'^user/(?P<user_id>\d+)/$', UserDetailView.as_view(), name='user_detail'),

# Match username with specific pattern


Python Framework

re_path(r'^profile/(?P<username>[a-zA-Z0-9_]+)/$', ProfileView.as_view(),
name='profile'),

# Optional parameter
re_path(r'^blog/(?P<year>\d{4})?/$', BlogArchiveView.as_view(),
name='blog_archive'),]

Regex Pattern Explanation:

 \d+: Matches one or more digits


 [a-zA-Z0-9_]+: Matches alphanumeric characters and underscores
 \d{4}: Matches exactly 4 digits
 ?P<name>: Named capture group
 ?: Makes the preceding pattern optional

Url Parameters, Extra Options, and Query Strings


 To handle url parameters Django uses Python’s standard regular expression
syntax for named groups

 Django url parameter definition for access in templates

urlpatterns=[
url(r'^drinks/(?P\D+)/',TemplateView.as_view(template_name='drinks/index. html')),

 Notice the (?P\D+) syntax in Listing above example.

 The ?P<> syntax tells Django to treat this part of the regular expression as a
named group and assign the value to a parameter named drink_name declared
between <>.

 The final piece \D+ is a regular expression to determine the matching value; in
this case the matching value is one or more non-digit characters,
Python Framework

Url Consolidation and Modularization

What is URL Consolidation?

URL consolidation is the process of organizing and structuring URL routing in a Django
project to:

 Improve code organization


 Enhance maintainability
 Create a clear and logical URL structure
 Reduce complexity in routing

Key Concepts of URL Consolidation


1. Hierarchical URL Configuration
Python Framework

2. App-Level URL Modularization

3. Namespace and Reverse Routing


 A project’s internal links or url references (e.g., Home Page) tend to be hard-
coded,
 whether it’s in view methods to redirect users to certain locations or in
templates to provide adequate user navigation.
 Hard-coding links can present a serious maintenance problem as a project
grows,
 because it leads to links that are difficult to detect and fix.
 Django offers a way to name urls so it’s easy to reference them in view
methods and templates.
 The most basic technique to name Django urls is to add the name attribute to
url definitions in urls. py.
Python Framework

4. Dynamic URL Pattern Generation

from django.urls import path, include


from django.conf import settings
from importlib import import_module

def generate_dynamic_urlpatterns():
"""
Dynamically generate URL patterns from installed apps
"""
dynamic_patterns = []

for app in settings.INSTALLED_APPS:


try:
# Attempt to import urls module from each app
urls_module = import_module(f'{app}.urls')

if hasattr(urls_module, 'urlpatterns'):
# Prefix app name to create consolidated routing
dynamic_patterns.append(
path(f'{app}/', include((f'{app}.urls', app)))
)
except (ImportError, AttributeError):
continue

return dynamic_patterns

# Add to project urls.py


urlpatterns += generate_dynamic_urlpatterns()
Python Framework

5. Nested URL Configurations

Benefits of URL Consolidation

 Improved Code Organization


 Enhanced Maintainability
 Clear Separation of Concerns
 Easier Scaling of Applications
 Simplified Routing Logic
 Better Performance

Common Challenges and Solutions

1. Avoiding URL Conflicts


o Use namespaces
o Create clear, distinct URL patterns
o Use app-specific prefixes
2. Managing Complex Routing
o Break down large URL configurations
o Use nested include() for related routes
o Leverage Django's flexible routing system
Python Framework

View Method Middleware

 In most circumstances, data in requests and responses is added, removed, or


updated in a piecemeal fashion in view methods.

 However, sometimes it’s convenient to apply these changes on all requests and
responses.

 For example, if you want to access certain data on all view methods, it’s easier to
use a middleware class to make this data accessible across all requests.

 Just as if you want to enforce a security check on all responses, it’s easier to do
so globally with a middleware class.

Built-In Middleware Classes


Default Django middleware classes in MIDDLEWARE

MIDDLEWARE = [

'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',

Custom Middleware

Step 1: Create auth_middleware.py:

# myapp/auth_middleware.py

from django.shortcuts import redirect

class AuthRequiredMiddleware:

def __init__(self, get_response):

self.get_response = get_response

def __call__(self, request):

# Restrict unauthenticated users

if not request.user.is_authenticated and

request.path.startswith('/dashboard/'):
Python Framework

return redirect('/login/')

response = self.get_response(request)

return response

Step 2: Add it to settings.py:

MIDDLEWARE = [

# Other middleware...

'myapp.auth_middleware.AuthRequiredMiddleware',

Step 3: Create basic views:

# myapp/views.py

from django.http import HttpResponse

def dashboard(request):

return HttpResponse("Welcome to the dashboard!")

def login_view(request):

return HttpResponse("Please log in.")

Step 4: Configure urls.py:

from django.urls import path

from .views import dashboard, login_view

urlpatterns = [

path('dashboard/', dashboard),

path('login/', login_view),

]
Python Framework

Add Flash Messages

Techniques to add Django flash messages(views.py)

from django.contrib import messages

# Generic add_message method

messages.add_message(request, messages.DEBUG, 'The following SQL statements were


executed: %s' % sqlqueries)

# Debug messages ignored by default

messages.add_message(request, messages.INFO, 'All items on this page have free


shipping.')

messages.add_message(request, messages.SUCCESS, 'Email sent successfully.')

messages.add_message(request, messages.WARNING, 'You will need to change your


password in one week.')

messages.add_message(request, messages.ERROR, 'We could not process your request


at this time.')

In HTML File

{% if messages %}

<ul class="messages">

{% for msg in messages %}

<li>

<div class="alert alert-{{msg.level_tag}}" role="alert">

{{msg.message}}

</div>

</li>

{% endfor %}

</ul>

{% endif %}
Python Framework

Django Template
Syntax

Django templates are written using a combination of HTML and template tags. Template
tags are enclosed in {% %} and are used to handle logic like loops, conditionals, and
variable rendering. Template variables are enclosed in {{ }}.

Example:
html
Copy code
<!DOCTYPE html>
<html>
<body>
<h1>{{ title }}</h1>
<p>{% if user.is_authenticated %}
Welcome, {{ user.username }}!
{% else %}
Please log in.
{% endif %}
</p>
</body>
</html>

 {{ title }}: Renders the value of the title variable.


 {% if %}: A conditional statement to check if a user is authenticated.

Template Configuration

To use Django templates in a project, you need to configure them in the settings.py file.
By default, Django uses the django.template.backends.django.DjangoTemplates
backend.

Configuration:

In settings.py, the TEMPLATES setting defines template directories, context processors,


and the backend used.

TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'templates')], # Template directory
'APP_DIRS': True, # Automatically look for templates in each app's 'templates'
folder
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
Python Framework

'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]

Reusable Template

Reusable templates are those that can be used across different pages or views. This is
often done by creating common header, footer, and navigation bar templates.

Example:

1. base.html (reusable base template)

html
Copy code
<!DOCTYPE html>
<html>
<head>
<title>{% block title %}My Website{% endblock %}</title>
</head>
<body>
<header>
<h1>Welcome to My Website</h1>
<nav>
<a href="/">Home</a> | <a href="/about/">About</a>
</nav>
</header>
<div>
{% block content %}
{% endblock %}
</div>
</body>
</html>

2. home.html (extends the base template)

{% extends "base.html" %}

{% block title %}Home{% endblock %}

{% block content %}
<h2>Home Page</h2>
<p>Welcome to the home page.</p>
{% endblock %}
Python Framework

Built-in Context Processors

Context processors are Python functions that take a request object and return a
dictionary of items to be added to the template context globally.

Built-in Context Processors:

 django.template.context_processors.debug: Provides debug information for


templates.
 django.template.context_processors.request: Adds the request object to the
context.
 django.contrib.auth.context_processors.auth: Adds user-related data (like user
and perms) to the context.
 django.contrib.messages.context_processors.messages: Adds message
framework data (messages) to the context.

Example of using the context processor:

<p>User: {{ user.username }}</p>


<p>Message count: {{ messages.count }}</p>

Custom Context Processors

You can define your own context processors by creating a Python function that takes
the request object and returns a dictionary of variables.

Custom Django context processors allow you to set up data for access on all Django
templates.

A Django custom context processor is structured just like a regular Python method with
an HttpRequest

object argument that returns a dictionary. The returning dictionary keys of the context
processor represent

template references and the dictionary values data objects (e.g., strings, lists,
dictionaries) accessible in templates.

Example:

1. Define a custom context processor:

# in myapp/context_processors.py
def get_site_name(request):
return {'site_name': 'My Awesome Website'}

2. Add it to settings.py:

TEMPLATES = [
Python Framework

{
'OPTIONS': {
'context_processors': [
'myapp.context_processors.get_site_name',
],
},
},
]

3. Using the context processor in a template:

html<p>Welcome to {{ site_name }}!</p>

Built-in Filters

Django filters are designed to format template variables. The syntax to apply Django
filters is the vertical bar character | also known as “pipe” in Unix environments (e.g.,
{{variable|filter}}).

It’s worth mentioning that it’s possible to use multiple filters on the same variable (e.g.,
{{variable|filter|filter}}).

Example:

 date: Formats a date.


 length: Returns the length of an object.
 lower: Converts a string to lowercase.

html
<p>Today's date: {{ current_date|date:"F j, Y" }}</p>
<p>Length of list: {{ my_list|length }}</p>
<p>{{ username|lower }}</p>

Common built-in filters:

 default: Sets a default value if a variable is empty.


 truncatewords: Truncates a string to a certain number of words.
 join: Joins a list with a given separator.

Template Tags

Template tags in Django allow for more complex logic. They are enclosed in {% %} and
can be used for loops, conditionals, and including other templates.

Common Tags:

 {% for %}: Loop over a list or dictionary.


 {% if %}: Conditional statements.
 {% include %}: Includes another template.
Python Framework

 {% block %}: Defines a block that can be overridden in child templates.

Example:
html
<ul>
{% for item in items %}
<li>{{ item }}</li>
{% empty %}
<li>No items available</li>
{% endfor %}
</ul>

{% if user.is_authenticated %}
<p>Welcome, {{ user.username }}!</p>
{% else %}
<p>Please log in.</p>
{% endif %}

Custom Filters

Django allows you to define custom filters that you can use in templates. Custom filters
are defined in Python files and then added to the template engine.

Example of creating a custom filter:

1. Create the custom filter:

# in myapp/templatetags/custom_filters.py
from django import template

register = template.Library()

@register.filter
def multiply(value, arg):
try:
return value * arg
except (ValueError, TypeError):
return value

2. Load and use the filter in a template:

{% load custom_filters %}

<p>{{ 5|multiply:3 }}</p> <!-- Output: 15 -->

~~~~~~~~~~~~~~~~~~~All The Best~~~~~~~~~~~~~~~~~~~~~

You might also like