Full Stack Development-Module 2
Full Stack Development-Module 2
In Django, templates are text files containing a mix of static HTML markup and
dynamic content generated using Django's template language. They serve as the
presentation layer of web applications, allowing developers to create dynamic web
pages by inserting data from the server side into predefined placeholders within
the HTML structure. Templates facilitate the separation of concerns between the
presentation layer and the business logic, promoting a clean and maintainable
codebase. Django's template system includes features like template tags, template
variables, template inheritance, and filters, providing developers with the tools
needed to create dynamic and interactive web applications efficiently.
Django Template System
The Django template system is a powerful tool for generating dynamic HTML content
in web applications. Here's an overview:
Purpose: The template system allows developers to separate the presentation layer
from the business logic in Django web applications. It facilitates the creation of
HTML pages with dynamic content by combining static HTML markup with template
tags, variables, filters, and control structures.
Syntax: Django templates use a syntax similar to Python, but with special constructs
for embedding dynamic content. Template variables are enclosed in double curly
braces ({{ }}), while template tags are enclosed in curly braces with percent signs
({% %}). Template tags control the logic and flow of the template, allowing for loops,
conditionals, includes, and more.
Filters: Filters modify the output of template variables or template tags. They allow
for formatting, manipulation, and customization of data displayed in the template.
Django provides a range of built-in filters for common tasks like date formatting,
string manipulation, and more. Custom filters can also be defined to suit specific
application requirements.
Overall, the Django template system provides a flexible and efficient way to create
dynamic HTML content in web applications, promoting code reuse, maintainability,
and separation of concerns.
Template Basics
Template Variables:
Definition: Template variables are placeholders within Django templates that
represent dynamic data to be rendered.
Example: Suppose you have a context dictionary in your view containing the following
data:
Python :
context = { 'name': 'John',
'age': 30,
'city': 'New York' }
Html:
<p>Name: {{ name }}</p>
<p>Age: {{ age }}</p>
<p>City: {{ city }}</p>
Template Basics
Template Tags:
Definition: Template tags are constructs within Django templates that control the
logic and flow of the template.
Filters:
Definition: Filters modify the output of template variables or template tags.
Example: Using the date filter to format a date
Here, birthday is a variable containing a date, and date:"F j, Y" formats it as "Month
Day, Year" (e.g., "January 1, 2023").
Template Basics
Blocks:
Definition: Blocks allow templates to be extended and overridden in a hierarchical
manner using template inheritance.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>{% block title %}My Site{% endblock %}</title>
</head>
<body>
{% block content %}
<p>This is the base content.</p>
{% endblock %}
</body>
</html>
Template Basics
Then, extend the base template in another template (child.html) and override the
blocks:
{% extends "base.html" %}
{% block content %}
<p>This is the content of the child page.</p>
{% endblock %}
Template Basics
Template Language: Django comes with its own template language that allows developers to
dynamically generate HTML pages. This language includes template tags, template
variables, filters, and control structures like loops and conditionals.
Template Files: In Django, templates are typically stored in the templates directory within each
Django app. These template files have a .html extension and contain a mix of HTML code
and Django template language syntax.
Rendering: Django uses a template engine to render templates and generate HTML
dynamically. The most commonly used template engine in Django is the Django Template
Language (DTL), but other engines like Jinja2 can also be integrated.
Context: Templates in Django are rendered with a context, which is a dictionary containing
data to be displayed in the template. Views in Django pass data to templates by creating a
context dictionary and rendering the template with that context.
create a base template with common layout and structure, and then extend
define a base design once and then customize it as needed for different
3.Extend Base Template: Use {% extends %} to inherit the base template in child
templates.
6.Render Child Template: Specify the child template in views, and Django will
combine it with the base template.
Model:
Define Relationships:
Establish relationships between models using ForeignKey,
OneToOneField, or ManyToManyField.
ForeignKey establishes a many-to-one relationship, OneToOneField
creates a one-to-one relationship, and ManyToManyField defines a
many-to-many relationship.
Defining and Implementing Models
4. Run Migrations:
• To create an object in Django, import the appropriate model class and instantiate
it by passing values for each field.
class Publisher(models.Model):
name = models.CharField(maxlength=30)
address = models.CharField(maxlength=50)
city = models.CharField(maxlength=60)
state_province = models.CharField(maxlength=30)
country = models.CharField(maxlength=50)
website = models.URLField()
from books.models import Publisher
Retrieving Objects:
The retrieved objects can be viewed as a list of model instances. By default, the
output shows a list of model objects.
print(publisher_list)
# Output: [<Publisher: Publisher object>, <Publisher: Publisher object>]
# Retrieving objects
publisher_list = Publisher.objects.all() # Executes: SELECT * FROM publisher
Adding Model String Representations
Purpose and Functionality:
class Book(models.Model):
title = models.CharField(max_length=100)
author = models.CharField(max_length=50)
publication_date = models.DateField()
def __str__(self):
return self.title
Adding Model String Representations
Creating Instances:
Create instances of the Book model and save them to the database
When you print a Book instance or view it in a list, Django uses the
__str__() method to display the title.
To insert a row into the database, instantiate your model class with the
necessary attributes using keyword arguments. This action does not
interact with the database.
p.save()
Inserting/Updating Data
3. SQL Translation:
The save() method translates to an SQL INSERT statement, adding the
record to the database with an autogenerated primary key.
p.id # e.g., 52
Inserting/Updating Data
5. Updating an Instance:
To update an existing record, modify the instance attributes and call the
save() method again, which performs an SQL UPDATE statement instead
of an INSERT.
2. Django's Simple Retrieval: Use all() method through the model's manager
(e.g., Publisher.objects.all()) to easily retrieve all data for a specific model.
4. Explicit Field Listing: Django prefers explicit field listing over implicit
retrieval, aligning with Pythonic principles and enhancing performance.
Publisher.objects.filter(name="Apress Publishing")
Filtering Data
Multiple Argument Filtering: You can pass multiple arguments into filter() to
further narrow down the data. These arguments are translated into SQL AND
clauses, allowing for more specific filtering.
Publisher.objects.filter(country="U.S.A.", state_province="CA")
Different Lookup Types: By default, Django uses the SQL = operator for exact match
lookups. However, other lookup types are available, such as __contains, which
translates to an SQL LIKE statement for partial string matches.
Publisher.objects.filter(name__contains="press")
Filtering Data
Special Lookup Types: Django supports various lookup types, including case-
insensitive matching (icontains), string prefix matching (startswith), string suffix
matching (endswith), and range queries (range). These provide versatile options
for filtering data based on specific criteria.
Usage of the get() Method: Utilize the get() method to retrieve a single object based
on specified criteria. For instance,
Publisher.objects.get(name="Apress Publishing")
fetches the publisher with the name "Apress Publishing".
Exception Handling for Multiple Objects: If the query results in multiple objects,
invoking get() will raise an exception.
For example,
Publisher.objects.get(country="U.S.A.")
will raise an AssertionError due to multiple matches.
Publisher.objects.get(name="Penguin")
will raise a DoesNotExist exception as there's no publisher with the name "Penguin".
Ordering Data
Multiple Field Ordering: Data can be ordered by multiple fields for more
nuanced sorting, as shown by Publisher.objects.order_by("country",
"address"), which orders publishers first by country and then by address.
Reverse Ordering: Reverse ordering is achievable by prefixing the field
name with a minus sign, as demonstrated by
Publisher.objects.order_by("-name"), sorting in reverse alphabetical order
by name.
Ordering Data
class Meta:
ordering = ["name"]
Ordering Data
class Meta:
ordering = ["name"]
Chaining Lookups
Chaining Lookups:
Chaining allows combining multiple QuerySet methods to refine
data retrieval.
This means you can filter the data first and then order the filtered
results, or vice versa.
Example:
Publisher.objects.filter(country="U.S.A.").order_by("-name")
filters publishers from the U.S.A. and then orders them by name in
descending order.
Slicing Data
Syntax: QuerySet[start:end]
where start is the starting index and end is the ending index.
Example:
Publisher.objects.all()[0] retrieves the first publisher.
Deleting Objects
Deleting Single Objects:
apress = Publisher.objects.get(name="Addison-Wesley")
apress.delete()
publishers = Publisher.objects.all()
publishers.delete()
class Book(models.Model):
title = models.CharField(max_length=100)
publication_date = models.DateField()
num_pages = models.IntegerField(blank=True, null=True)
authors = models.ManyToManyField(Author)
*Add the Admin Class:
Add an inner Admin class to the model. This class can be empty for now (using
pass), which indicates that the model should be included in the admin interface
with default options.
class Book(models.Model):
title = models.CharField(max_length=100)
publication_date = models.DateField()
num_pages = models.IntegerField(blank=True, null=True)
authors = models.ManyToManyField(Author)
class Admin:
pass
(or) Model Registration:
You can register your models with the admin interface to make
them manageable via the admin site. This is done using the
admin.site.register() function. from django.contrib import admin
from .models import Book
admin.site.register(Book)
Step 2: Install the Admin Application
To use the admin interface, you need to add the admin application to
your project settings and sync the database:
*Modify INSTALLED_APPS:
o Open your settings.py file and add django.contrib.admin to the
INSTALLED_APPS list
INSTALLED_APPS = [
...
'django.contrib.admin',
...
]
urlpatterns = [
...
path('admin/', admin.site.urls),
...
]
Step 4 : Running the Development Server
Start your development server:
Create or update the admin.py file in your app directory. This file
is used to register your models with the admin site and customize
their display.
from django.contrib import admin
from .models import Book, Publisher, Author
class BookAdmin(admin.ModelAdmin):
list_display = ('title', 'publisher', 'publication_date')
list_filter = ('publisher', 'publication_date')
ordering = ('-publication_date',)
search_fields = ('title',)
admin.site.register(Book, BookAdmin)
admin.site.register(Publisher)
admin.site.register(Author)
Explanation:
Imports: Import the admin module and your models (Book,
Publisher, Author).
BookAdmin Class:
o list_display = ('title', 'publisher', 'publication_date'): Specifies
the columns to display in the list view for the Book model.
o list_filter = ('publisher', 'publication_date'): Adds filters for
publisher and publication_date on the right side of the list
view.
o ordering = ('-publication_date',): Orders the books by
publication_date in descending order.
o search_fields = ('title',): Adds a search box to search by title.
Registration: Register the Book model with the custom
BookAdmin class. Also, register the Publisher and Author models
with the admin site.
create a Django model for an employee and
customize it to include search functionality,
list display options, and add filters, you can
follow these steps:
# models.py
from django.db import models
class Employee(models.Model):
first_name = models.CharField(max_length=50)
last_name = models.CharField(max_length=50)
email = models.EmailField(unique=True)
department = models.CharField(max_length=100)
job_title = models.CharField(max_length=100)
date_hired = models.DateField()
salary = models.DecimalField(max_digits=10, decimal_places=2)
def __str__(self):
return f"{self.first_name} {self.last_name}
# admin.py
from django.contrib import admin
from .models import Employee
class EmployeeAdmin(admin.ModelAdmin):
admin.site.register(Employee, EmployeeAdmin)
Django Model Fields
Django Model Fields
Django Model Relationship Fields
Django Model Field Options
class Author(models.Model):
id = models.AutoField(primary_key=True) # primary_key example
name = models.CharField(max_length=100)
email = models.EmailField(unique=True, null=True, blank=True) # null and blank
example
class Book(models.Model):
title = models.CharField(max_length=200)
author = models.ForeignKey(Author, on_delete=models.CASCADE)
published_date = models.DateField(null=True, blank=True) # null and blank example
price = models.FloatField(default=0.0) # default example
status = models.CharField(
max_length=1,
choices=[
('D', 'Draft'),
('P', 'Published'),
('W', 'Withdrawn')
],
default='D' # choices and default example
)
description = models.TextField(blank=True) # blank example
Customizing Admin Interfaces in Django
Search Fields:
o Enables searching through specified fields in the admin list
view.
o Enhances data retrieval efficiency.
List Display:
o Specifies which fields are displayed in the admin list view.
o Provides an at-a-glance overview of key information.
List Filter:
o Adds filters to the admin sidebar.
o Allows for quick data filtering based on field values.
Ordering:
o Defines the default order of records in the list view.
o
Permissions:
Manages user access to different parts of the admin
interface.
Ensures data security and role-based access control.
Read-Only Fields:
Specifies fields that should be read-only in the form
view.
Prevents modification of certain data by users.
Customizing the Admin Interface for the Book Model in Django