Module-02 FSD Search Creators
Module-02 FSD Search Creators
Module-02 FSD Search Creators
Module-02
Template-System Basics
2. Common Use:
• HTML Generation: Typically used to generate HTML documents, but can generate
any text-based format.
• The example given creates an HTML page to thank a person for placing an order.
<html>
<head><title>Ordering notice</title></head>
<body>
<h1>Ordering notice</h1>
<ul>
{% endfor %}
</ul>
{% if ordered_warranty %}
{% else %}
{% endif %}
</body>
</html>
HTML Structure:
Basic Steps
c = template.Context({'name': 'Fred'})
print(t.render(c)) # Output: My name is Fred.
Detailed Steps
Rendering a Template:
Complex Example:
t = Template(raw_template)
c = Context({
'person_name': 'John Smith',
'company': 'Outdoor Equipment',
'ship_date': datetime.date(2009, 4, 2),
'ordered_warranty': False
})
print(t.render(c))
# Output:
# <p>Dear John Smith,</p>
# <p>Thanks for placing an order from Outdoor Equipment. It's scheduled to
# ship on April 2, 2009.</p>
# <p>You didn't order a warranty, so you're on your own when
# the products inevitably stop working.</p>
# <p>Sincerely,<br />Outdoor Equipment</p>
Tags
1. if/else Tag:
• Evaluates a variable to determine if it is True.
• Displays content between {% if %} and {% endif %} if the variable is True.
• Supports {% else %} for alternate content.
• Allows and, or, and not for multiple conditions, but does not support combined
logical operators.
• Nested {% if %} tags can be used for complex conditions.
Example:
{% if today_is_weekend %}
{% else %}
{% endif %}
2. for Tag:
• Iterates over each item in a sequence.
• Syntax: {% for X in Y %} where Y is the sequence and X is the variable for each
iteration.
• Supports reversed for reverse iteration.
• Can nest {% for %} tags and supports {% empty %} for handling empty lists.
• Provides a forloop variable with attributes like counter, counter0, revcounter,
revcounter0, first, last, and parentloop.
<ul>
{% for athlete in athlete_list %}
<li>{{ athlete.name }}</li>
{% endfor %}
</ul>
3. ifequal/ifnotequal Tag:
• Compares two values and displays content if they are equal or not equal.
• Supports an optional {% else %} tag.
• Accepts hard-coded strings, integers, and decimal numbers as arguments but not
complex data types.
Example:
Example:
{# This is a comment #}
{% comment %}
This is a
multiline comment.
{% endcomment %}
1. addslashes:
• Adds a backslash before backslashes, single quotes, and double quotes
Example
{{ text|addslashes }}
2. date:
• Formats a date or datetime object according to a format string.
Example:
{{ pub_date|date:"F j, Y" }}
3. length:
• Returns the length of a value (number of elements in a list or characters in a string).
Example:
{{ items|length }}
4. lower:
• Converts a string to lowercase.
Example:
{{ name|lower }}
Model:
Example:
# models.py
class Book(models.Model):
title = models.CharField(max_length=200)
author = models.CharField(max_length=100)
publication_date = models.DateField()
• The View handles the business logic and controls the flow of the application.
• It receives requests from the user, interacts with the Model to fetch or update data, and
renders the appropriate Template.
• Views are Python functions or classes that receive HTTP requests and return HTTP
responses.
Example:
# views.py
def book_list(request):
books = Book.objects.all()
Template:
• The Template is responsible for presenting the data to the user in an HTML format.
• It defines the structure and layout of the web page.
• Templates are written using Django's template language, which provides tags and filters to
control the rendering of dynamic content.
<!DOCTYPE html>
<html>
<head>
<title>Book List</title>
</head>
<body>
<h1>Book List</h1>
<ul>
{% endfor %}
</ul>
</body>
</html>
Template Loading
Template Inheritance
Example:
{% extends "base.html" %}
{% block content %}
{% endblock %}
Example:
{% extends "base.html" %}
{% block content %}
{% endblock %}
By defining a clear hierarchy of templates, developers can streamline the development process
and ensure consistency in the site's appearance and behavior.
• Django follows the MVC pattern, where "Model" represents the data access layer,
"View" handles presentation logic, and "Controller" decides which view to use
based on user input.
Breakdown in Django:
• Model (M): Handled by Django's database layer, including data access, validation,
behaviors, and relationships.
• View (V): Handled by views and templates, responsible for selecting and
displaying data on the web page or document.
• Controller (C): Managed by the framework itself, following URLconf and calling
appropriate Python functions based on user input.
MTV Framework:
• Django is sometimes referred to as an MTV framework, where "M" stands for "Model,"
"T" for "Template," and "V" for "View."
• Model (M): Represents the data access layer, covering everything about data and its
relationships.
• Template (T): Represents the presentation layer, handling how data should be displayed on
a web page.
• View (V): Represents the business logic layer, acting as a bridge between models and
templates.
• In Django, views describe the data presented to the user, including which data is displayed,
not just how it looks.
• Contrary to frameworks like Ruby on Rails, where controllers decide which data to present,
Django views are responsible for accessing models and deferring to appropriate templates.
Underlying Concepts:
• Both interpretations of MVC (Django's and others like Ruby on Rails) have their validity,
and the key is to understand the underlying concepts rather than adhering strictly to one
interpretation.
Configuring Databases
Initial Configuration:
Database Settings:
• DATABASE_ENGINE: Specifies the database engine to use. Must be set to one of the
available options (e.g., PostgreSQL, MySQL, SQLite).
• DATABASE_NAME: Specifies the name of the database. For SQLite, specify the full
filesystem path.
• DATABASE_USER: Specifies the username to use for database access.
• DATABASE_PASSWORD: Specifies the password for database access.
• DATABASE_HOST: Specifies the host for the database server. If using SQLite or the
database is on the same computer, leave this blank.
• DATABASE_PORT: Specifies the port for the database server.
Testing Configuration:
• After configuring the database settings, it's recommended to test the configuration.
• Use the Django shell (python manage.py shell) to test the connection.
• Import connection from django.db and create a cursor.
• If no errors occur, the database configuration is correct.
• Errors may occur if settings are incorrect or if required database adapters are missing.
• Solutions include setting correct values for settings, installing required adapters, and
ensuring database existence and user permissions.
• Django models represent the "M" in the MTV (or MVC) pattern, standing for "Model."
• They describe the data in the database using Python code.
• Models serve as the equivalent of SQL CREATE TABLE statements but in Python.
• Django executes SQL code behind the scenes based on these models.
• Models return Python data structures representing rows in database tables.
• They also represent higher-level concepts that SQL alone may not handle effectively.
Introspection Overhead:
• Introspecting the database at runtime incurs overhead, especially for each request or server
initialization.
• Django opts for explicit Python model definitions to reduce this overhead.
Maintaining Context:
• Storing models as Python code facilitates version control, making it easier to track changes
to data layouts.
• Django models offer higher-level data types (e.g., for email addresses, URLs) that SQL
may lack.
• Consistency Across Database Platforms:
• Distributing a Python module describing data layouts is more pragmatic than separate sets
of SQL statements for different databases.
Introduction:
• The example focuses on these entities due to their well-known conceptual relationships.
• Books, authors, and publishers form a common data layout used in introductory SQL
textbooks.
• An author entity comprises fields for first name, last name, and email address.
• A publisher entity includes fields for name, street address, city, state/province, country,
and website.
• A book entity contains fields for title, publication date, and relationships with authors and
a single publisher.
• In the models.py file of the Django app (created using the startapp command), the
following Python code is entered:
class Publisher(models.Model):
name = models.CharField(max_length=30)
address = models.CharField(max_length=50)
city = models.CharField(max_length=60)
state_province = models.CharField(max_length=30)
country = models.CharField(max_length=50)
class Author(models.Model):
first_name = models.CharField(max_length=30)
last_name = models.CharField(max_length=40)
email = models.EmailField()
class Book(models.Model):
title = models.CharField(max_length=100)
authors = models.ManyToManyField(Author)
publisher = models.ForeignKey(Publisher)
publication_date = models.DateField()
);
• Django can automatically generate the above SQL CREATE TABLE statement based on
the model definitions.
• This automation simplifies the process of creating and managing database tables, reducing
the manual effort required.
Many-to-Many Relationships:
• In the case of many-to-many relationships, such as the authors field in the Book model,
Django creates an additional table (a "join table").
• This join table facilitates the mapping of books to authors without directly adding an
authors column to the Book table.
• Django automatically assigns a primary key to each model if not explicitly defined.
• The default primary key is an autoincrementing integer field named id.
• Django ensures that each model has a single-column primary key, which is a requirement
for data integrity.
p1.save()
p2.save()
publisher_list = Publisher.objects.all()
print(publisher_list)
• The provided Python code demonstrates basic data access using Django's high-level
Python API.
• Publisher.objects.all() fetches all the Publisher objects from the database.
• The objects are retrieved as a queryset, which is a collection of database objects of a
particular model.
• The print(publisher_list) statement displays the list of Publisher objects retrieved from the
database. However, the output may appear as [<Publisher: Publisher object>, <Publisher:
Publisher object>], as shown in the example, because Django doesn't automatically provide
a human-readable representation of objects. To display meaningful information, you can
define a __str__() method in the Publisher model class.
class Publisher(models.Model):
name = models.CharField(max_length=30)
address = models.CharField(max_length=50)
city = models.CharField(max_length=60)
state_province = models.CharField(max_length=30)
country = models.CharField(max_length=50)
website = models.URLField()
def __str__(self):
class Author(models.Model):
first_name = models.CharField(max_length=30)
last_name = models.CharField(max_length=40)
email = models.EmailField()
def __str__(self):
return f"{self.first_name} {self.last_name}"
class Book(models.Model):
title = models.CharField(max_length=100)
authors = models.ManyToManyField(Author)
publisher = models.ForeignKey(Publisher, on_delete=models.CASCADE)
publication_date = models.DateField()
def __str__(self):
return self.title
6. Importance of __str__():
• Ensure that every model you define has a __str__() method to provide a meaningful
string representation of objects.
• Django uses this method's output in various situations where it needs to display
objects, enhancing usability and readability.
•
1. Definition of Unicode Objects:
• Unicode objects in Python are strings that can handle a wide range of characters,
including accented Latin characters, non-Latin characters, curly quotes, and
obscure symbols.
• They can represent over a million different types of characters.
2. Encoding Comparison:
• Normal Python strings are encoded, meaning they use encodings like ASCII, ISO-
8859-1, or UTF-8.
• Handling fancy characters in normal strings requires tracking the encoding, or
else the characters might appear incorrectly when displayed.
• Mixing different encodings can lead to encoding problems, such as displaying
"???" or other odd characters.
Inserting Data:
• To insert a row into the database using Django models, create an instance of the
model class with keyword arguments representing the field values.
• Instantiating the model class does not immediately affect the database.
• Data is inserted into the database by calling the save() method on the model
instance.
Example:
p = Publisher(name='Apress',
city='Berkeley',
state_province='CA',
country='U.S.A.',
website='http://www.apress.com/')
p.save()
Equivalent SQL:
• When saving a new record, Django calculates and sets the primary key value for
the record.
• Subsequent calls to save() update the existing record in the database instead of
creating a new one.
Updating Data:
• To update data, modify the fields of the model instance and then call save() again.
• All fields are updated, not just the ones that have been changed, which may lead to race
conditions in some scenarios.
Example of Update:
Considerations:
• Depending on the application, updating all fields may cause race conditions.
• Strategies for updating multiple objects in one statement are available, which can be more
efficient in certain scenarios.
Selecting Objects:
• In web applications, querying existing database records is often more common than
creating new ones.
• The process of retrieving all records for a given model in Django.
Publisher.objects.all ()
Equivalent SQL:
• The Django code above roughly translates to the following SQL query.
Components of Publisher.objects.all():
• Publisher: Refers to the model for which data is being looked up.
• objects: Represents a manager, which handles table-level operations on data, including
data lookup. Every model automatically gets an objects manager.
• all(): A method on the objects manager that returns all rows in the associated database
table. It returns a QuerySet object.
QuerySets:
General Pattern:
• Any database lookup in Django follows the pattern of calling methods on the manager
attached to the model being queried.
• It's common to need a subset of data from the database rather than retrieving everything
at once.
• Django's API allows filtering of data using the filter () method.
Usage:
• The filter () method takes keyword arguments, which are translated into SQL
WHERE clauses.
Example:
Publisher.objects. filter(name='Apress')
FROM books_publisher
• The get() method retrieves a single object from the database that matches the specified
criteria.
Example:
Publisher.objects.get(name="Apress")
Example:
Publisher.objects.get(country="U.S.A.")
Example:
Publisher.objects.get(name="Penguin")
Exception Handling:
Example:
try:
p = Publisher.objects.get(name='Apress')
except Publisher.DoesNotExist:
else:
Exceptions Details:
• To delete a single object from the database, call the object’s delete() method.
Example:
p = Publisher.objects.get(name="O'Reilly")
p.delete()
Bulk Deletion:
• Objects can also be deleted in bulk by calling delete() on the result of any QuerySet.
Example:
Publisher.objects.filter(country='USA').delete()
Publisher.objects.all().delete()
• The first line deletes all objects with the country set to 'USA', while the second line deletes
all objects from the Publisher table.
Precautions:
• Django requires explicit use of all() if you want to delete everything in a table to prevent
accidental deletion of all data.
Example:
Publisher.objects.all().delete()
• Deleting all data from a table without using all() will result in an AttributeError.
Example:
Publisher.objects.filter(country='USA').delete()
• This line deletes only the objects where the country is set to 'USA'.
Schema Evolution
• Understand the concept of a database schema and how it represents the structure of a
database.
• Learn about tables, columns, data types, primary keys, and foreign keys.
• Understand how Django models map to database tables and how model fields correspond
to table columns.
• Learn about Django's migration system and how it helps manage schema changes over
time.
• Learn how to add new fields to an existing model and create migrations for the same.
• Understand the concept of default values and how to handle existing data when adding new
fields.
• Learn how to modify the properties of existing fields (e.g., changing field types, max
lengths, etc.).
• Understand the implications of modifying fields and how to handle existing data during
field modifications.
• Learn how to remove fields from a model and create migrations for the same.
• Understand the implications of removing fields and how to handle data loss or data
preservation.
Renaming Fields:
• Learn the process of renaming fields in Django, as it doesn't provide a direct way to do so.
• Understand the concept of creating a new field, migrating data, and removing the old field.
Data Migrations:
• Learn about Django's RunPython operation in migrations, which allows executing custom
Python code during schema changes.
• Understand how to use data migrations to handle complex data transformations or custom
logic during schema evolution.
• Learn about testing strategies for schema changes, including creating backups and running
migrations in a staging environment.
• Understand the importance of thoroughly testing migrations before applying them to a
production database.
• Learn about best practices for schema evolution, such as incremental changes,
documenting changes, and maintaining backward compatibility.
• Understand the importance of version control and collaboration when managing schema
changes in a team environment.