Unit-1 Pythone Framework
Unit-1 Pythone Framework
Semester II
Unit-1
Django – URLs and Views: URL – Regular expressions, Parameters and Query
views
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.
• 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 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
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.
Repetition might be good to emphasize a point, but when it comes to web development,
it just leads to additional and time-consuming work.
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.
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
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.
5. Template Rendering
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.
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
Besides configuring Django to connect to a database, you’ll also need to install the
necessary Python packages to communicate with your database brand
Example
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)
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.
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.
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,
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
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)
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
<html>
<body>
</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
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',
'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
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.
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:
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:
The Django admin site provides a web-based interface to access the database connected
to a Django project.
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-5 Next, let’s create a Django superuser or administrator to access the Django
admin via the interface in
Password:
Password (again):
Password:
Password (again):
URL.PY
urlpatterns = [
# Match a numeric ID
re_path(r'^user/(?P<user_id>\d+)/$', UserDetailView.as_view(), name='user_detail'),
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'),]
urlpatterns=[
url(r'^drinks/(?P\D+)/',TemplateView.as_view(template_name='drinks/index. html')),
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 is the process of organizing and structuring URL routing in a Django
project to:
def generate_dynamic_urlpatterns():
"""
Dynamically generate URL patterns from installed apps
"""
dynamic_patterns = []
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
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.
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
# myapp/auth_middleware.py
class AuthRequiredMiddleware:
self.get_response = get_response
request.path.startswith('/dashboard/'):
Python Framework
return redirect('/login/')
response = self.get_response(request)
return response
MIDDLEWARE = [
# Other middleware...
'myapp.auth_middleware.AuthRequiredMiddleware',
# myapp/views.py
def dashboard(request):
def login_view(request):
urlpatterns = [
path('dashboard/', dashboard),
path('login/', login_view),
]
Python Framework
In HTML File
{% if messages %}
<ul class="messages">
<li>
{{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>
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:
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:
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>
{% extends "base.html" %}
{% block content %}
<h2>Home Page</h2>
<p>Welcome to the home page.</p>
{% endblock %}
Python Framework
Context processors are Python functions that take a request object and return a
dictionary of items to be added to the template context globally.
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:
# 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',
],
},
},
]
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:
html
<p>Today's date: {{ current_date|date:"F j, Y" }}</p>
<p>Length of list: {{ my_list|length }}</p>
<p>{{ username|lower }}</p>
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:
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.
# 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
{% load custom_filters %}