0% found this document useful (0 votes)
4 views

in deep of django framework

The document discusses the Django Template System, emphasizing the importance of separating design from code to facilitate independent work by programmers and designers. It outlines how Django templates allow for dynamic content rendering using placeholders and context, along with basic template tags and filters for logic and data manipulation. Additionally, it covers best practices for template management, including loading templates efficiently and using template inheritance to avoid code duplication.

Uploaded by

brsmce007
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

in deep of django framework

The document discusses the Django Template System, emphasizing the importance of separating design from code to facilitate independent work by programmers and designers. It outlines how Django templates allow for dynamic content rendering using placeholders and context, along with basic template tags and filters for logic and data manipulation. Additionally, it covers best practices for template management, including loading templates efficiently and using template inheritance to avoid code duplication.

Uploaded by

brsmce007
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 118

The Django Template

System
Module - 3
Separation of Design and Code in Django
• Hard-Coded HTML in Python
• Previous example views had
HTML directly in Python code.
• Problems with Hard-Coding HTML:
• Frequent design changes: Design changes more often than Python code,
requiring constant updates to the code.
• Separation of Responsibilities:
• Web development typically splits tasks:
• Python programming vs HTML/CSS design.
• Designers shouldn’t need to edit Python code.
• Parallel Development:
• Programmers and designers should work independently, not wait on each other
to edit combined code.
Solution: Django’s Template System
• A Django template is a string of text that is intended to separate the
presentation of a document from its data.
• A template defines placeholders and various bits of basic logic (i.e.,
template tags) that regulate how the document should be displayed.
• Usually, templates are used for producing HTML, but Django
templates are equally capable of generating any text-based format.
• Let’s dive in with a simple example template.
• This template describes an HTML page that thanks a person for
placing an order with a company. Think of it as a form letter:
Using the Template System
• Django’s template system works independently of views.
• Django’s template system is a Python library usable not just with
Django views. It can be used outside as well.
• Basic Use of Django’s Template System:
• Create a Template Object:
• Provide raw template code as a string.
• Render the Template:
• Use the render() method with a set of variables (context).
• Returns a fully rendered template as a string with evaluated variables and tags.

• Change context to render different


outputs:
• Context({'name': 'Fred'}) results in: "My name
is Fred."
Creating Template Objects
• Easiest method: Instantiate the Template object directly.
• The Template class is found in the django.template module.
• The constructor takes raw template code as an argument.
• Steps for creating a template object:
Template Compilation & Syntax Errors
• The template system compiles raw code into an optimized internal
form.
• Syntax errors during template creation will raise a
TemplateSyntaxError exception.
Rendering a Django Template
• After creating a Template object, pass it data via a context.
• A context is a set of template variable names and their values.
• The Context class lives in the django.template module and accepts a
dictionary.
• Use the render() method to fill the template with context data.
• Context Variable Names:
• Must begin with a letter (A–Z or a–z).
• May contain letters, digits, underscores, and dots.
• Case-sensitive.
Template Compilation and
Rendering Example:
• Output:

• The ordered_warranty evaluated to False, so the else block was


rendered.
• Date formatting: 'F j, Y' displays as April 2, 2009.
• Output contains \n for newlines, as shown in the Python interactive
interpreter.
Recap of steps:
• Write a template string.
• Create a Template object.
• Create a Context object.
• Call render() to get the filled template.
Using Multiple Contexts with the Same Template

• Template object can render different contexts.


• Example:
• Efficient Template RenderingBest Practice:
• Create the Template object once and render multiple contexts:
• Inefficient Code (creates Template object repeatedly):
Context Variable Lookup in
Django
• Dot character (.)Templates
is the key to traversing complex data structures in
Django templates.
• Dot allows access to:
• Dictionary keys
• Object attributes
• Object methods
• List indices
• Dictionary Key Access:
• Object Attribute Access

• Custom Class Attribute Access


• Object Method Access
• Note: No parentheses for method calls, and no arguments are allowed.
• List Index Access

• Dot Lookup Logic


• Dictionary lookup (e.g., foo["bar"])
• Attribute lookup (e.g., foo.bar)
• Method call (e.g., foo.bar())
• List-index lookup (e.g., foo[2])
• Short-circuit logic: Stops at the first valid match.
• Nested Dot Lookups
• Method Call Behavior
• Method calls are more complex than other lookup types.
• Key points to consider:
• If a method raises an exception during lookup, it will propagate unless the exception has a
silent_variable_failure attribute set to True.
• Example: Raises AssertionError vs. SilentAssertionError.
• If silent_variable_failure is True, the variable will render as an empty string.
• Method Call Behavior
• Method calls will work only if the method has no required arguments.
• Methods with side effects (e.g., delete()) should not be accessible in templates.
• To prevent this, set alters_data = True on the method.
• Example: The template system won’t execute the delete() method when {{ account.delete }} is
included in a template.
• Playing with Context Objects
• Context objects are usually instantiated by passing a dictionary to Context().

• Context objects are usually instantiated by passing a dictionary to Context().


• Deleting an Item:

• Adding a new variable:


Basic Template Tags and Filters
• Django comes with built-in tags and filters.
• This section provides a rundown of common tags.
• Tags: if/else:
• The {% if %} tag evaluates a variable, and if it’s "true," it displays content
between {% if %} and {% endif %}.

• The {% else %} tag is optional:


• Example:
• Logical Operators in if Tags
• You can use and, or, and not for testing multiple variables or negating a
variable.
• Example:

• Nested {% if %} tags are used for complex logic:


• Example:
• Notes:
• Invalid usage: {% if athlete_list and coach_list or cheerleader_list %}
(Ambiguous logic).
• Combine logic in the view code for clarity if needed.
• Use nested {% if %} tags for complex logic.
• Example for nested conditions:
• Close each {% if %} with an
{% endif %} to avoid
TemplateSyntaxError.
• FOR:
• {% for %} tag: Used to loop over each item in a sequence.
• Syntax: for X in Y, where X is the loop variable, and Y is the sequence.
• Everything between {% for %} and {% endfor %} is rendered for each loop iteration.
• Example: Looping through athlete_list:

• Reversed Loop
• Add reversed to loop in reverse order:
• Nesting for Tags
• Example of nested loops:

• No Support for break or continue:


• Django templates don't support breaking out of loops early or continuing the next
iteration.
• Magic forloop Variable
• The forloop variable provides useful attributes:
• forloop.counter: 1-indexed counter.
• forloop.counter0: 0-indexed counter.
• forloop.revcounter: Countdown of remaining items.
• forloop.revcounter0: 0-indexed reverse counter.
• forloop.first: Boolean, True if it's the first iteration.
• forloop.last: Boolean, True if it's the last iteration.
• Nested Loops: Accessing Parent Loop
• forloop.parentloop: Access the parent loop inside nested loops
• Example:
ifequal/ifnotequal
• Django template system limits programming functions; does not allow
arbitrary Python statements.
• Common need: Compare two values and display content if equal.
• {% ifequal %} tag is available to handle these comparisons.
• Using {% ifequal %} Tag:
• Compares two values.
• Displays content between {% ifequal %} and {% endifequal %} if values are
equal.
• Example:
• Hard-Coding Strings with ifequal
• Arguments can be hard-coded as strings.
• Valid examples:

• Using {% else %} with {% ifequal %}


• Supports optional {% else %} statement.
• Example:
• Allowed Argument Types
• Arguments can include:
• Template variables, strings, integers, and decimal numbers.
• Valid examples:

• Invalid Argument Types for ifequal


• Cannot use Python dictionaries, lists, or Booleans directly.
• Invalid examples:

•For true/false tests, use the {% if %} tag instead of {% ifequal %}.


Comments in Django Templates
• Similar to HTML and programming languages (e.g., Python), Django
allows comments in templates.
• To add a comment, use {# #}:
• Example:

• Comments do not appear in the rendered output.


• Single-Line Limitation
• Comments cannot span multiple lines.
• This limitation is intentional to enhance template parsing performance.
• Example:

• Output: The comment tag will not be parsed, and the comment content will appear in the output.
Filters in Django Templates
• Template filters: Modify variable values before display.
• Syntax: {{ variable|filter }}
• Example: {{ name|lower }} converts name variable to lowercase.
• Chaining Filters
• Filters can be chained to apply multiple filters sequentially.
• Example:
{{ my_text|escape|linebreaks }}
• Escapes text and converts line breaks to <p> tags.
Filters with Arguments
• Some filters accept arguments.
• Syntax: {{ variable|filter:"argument" }}
• Example: {{ bio|truncatewords:"30" }}
• shows first 30 words of bio.
Key Filters
• addslashes: Adds backslashes before \, ', or ".
• Useful for JavaScript strings.
• date: Formats dates using a specified format string.
• Example: {{ pub_date|date:"F j, Y" }}
• Format details in Appendix F.
• escape: Converts special characters to XML/XHTML-safe entities.
• Converts:
• & to &amp;
• < to &lt;
• > to &gt;
• " to &quot;
• ' to &#39;
• length: Returns length of a list, string, or any object with a __len__()
method
Using Templates in Views
• 1. Directly Embedding Templates in Code
• Initial approach: Embed template directly in Python code.

Drawback: Template remains embedded in the code, making it harder to manage.


• 2. Separating Template File
• Moving template to an external file:
• Save the template in a separate HTML file, like mytemplate.html.
• Example:
• Limitations of File-Reading ApproachMoving template to an external file:
1. No File Handling:
• Doesn’t handle missing files (raises IOError if file is missing).
2. Hard-Coded Path:
• Template path is hard-coded, making it inflexible.
• Duplicates paths across views.
3. Excessive Boilerplate Code:
• Repeated code for opening, reading, and closing files.
• Inefficient, time-consuming.
• Solution: Use Django’s Template Loading System and Template
Directories
• Centralizes templates and paths.
• Removes need for direct file-handling code.
• More organized and scalable for multiple templates.
• This approach organizes templates efficiently and reduces code
repetition across views.
Template Loading with Django
• Configuring Template Directory:
• Specify where templates are stored using the TEMPLATE_DIRS setting in your
settings.py file.
• Example:

• Points to Remember:
• Use absolute paths for template directories.
• For Windows, specify the drive letter and use forward slashes (/).
• Use a tuple for immutability or a list to avoid the trailing comma.
Using get_template() for Loading Templates
• Replacing Hard-Coded Paths:
• Django’s get_template() function loads templates without manual file
handling.
• Example:

• get_template() finds the template by combining TEMPLATE_DIRS and


the specified template name.
• Error Handling:
• If the template is missing, get_template() raises a TemplateDoesNotExist
error.
• Debugging:
• When DEBUG = True, Django shows a template-loader postmortem with error
details, helping pinpoint issues.
render_to_response(): A Shortcut for Rendering Templates

• Purpose:
• render_to_response() is a Django shortcut for common operations:
• Loading a template
• Creating a context
• Rendering the template with context
• Returning an HttpResponse object
• All these steps are simplified into one line of code.
• Example Code:
Benefits of Using
render_to_response():
• Simplifies Code: Eliminates the need for importing get_template,
Template, Context, and HttpResponse.
• Reduces Boilerplate: Only the template name and a context
dictionary are required.
• Auto-Generated HttpResponse: The function automatically creates an
HttpResponse, so you don’t need to specify it.
• Arguments:
• First Argument: Template name as a string (e.g., 'current_datetime.html').
• Second Argument: Context dictionary (e.g., {'current_date': now}) for
dynamic content.
• If no context is needed, you can skip the second argument, and an empty
dictionary will be used.
Using locals() in Django Views
• Original Code Without locals(): Here's an example of a view that uses
a traditional context dictionary:
• Refactored Code Using locals(): Now, let's simplify the above view
using locals():
• 1. The Concept of Template Inheritance
• Instead of copying and pasting the same code into multiple templates, you
define a base template that contains all the common HTML structure. Then,
you create child templates that extend the base template and fill in only the
parts that are different.
Interacting with a
Database:

Models
Understanding Django's MTV Development Pattern

• Django is designed with a specific development architecture to


promote the separation of different application concerns, making it
easier to maintain and extend projects.
• This architecture is commonly known as the Model-View-Controller
(MVC) pattern, though Django follows its own variant called the MTV
(Model-Template-View) pattern.
The MVC Pattern
• Model: Manages data and business logic. It handles data retrieval,
validation, and relationships.
• View: Represents the UI and presentation layer. It determines how
data is displayed to the user.
• Controller: Handles user inputs, interacts with the model, and decides
which view to render based on user actions.
The MTV Pattern in Django
The "Dumb" Way vs. The Django
Way
• When working with databases in Django, there are different approaches to fetching and
managing data.
• Let's explore the differences between a "dumb" way of querying databases and the streamlined
approach Django provides using its database API.
First Model
• Lets define models (database tables) for a simple use case involving
books, authors, and publishers.
• We'll explore the following relationships:
• One-to-Many Relationship: A book has a single publisher.
• Many-to-Many Relationship: A book can have multiple authors, and an author can write
multiple books.
• Each model generally corresponds to a single database table.
• Each attribute on a model generally corresponds to a column in that
database table.
• The attribute name corresponds to the column’s name, and the type
of field (e.g., CharField) corresponds to the database column type
(e.g., varchar).
• For example, the Publisher model is equivalent to the following table
(assuming PostgreSQL CREATE TABLE syntax):
Installing the Model
• Activate Models in Django Project:
• To create tables in the database, first activate the app by adding it to the list
of installed apps in the settings.py file.
• Validate the model:
py manage.py check
• The validate command checks whether your models’ syntax and logic are
correct.
• If all is well, you’ll see the message 0 errors found.
• If you don’t, make sure you typed in the model code correctly. The error
output should give you helpful information about what was wrong with the
code.
• Create the tables:
• python manage.py syncdb (Deprecated)
• New Commands:
• py manage.py makemigrations
• Prepares for migrations in migrations directory
• Py manage.py migrate
• Creates the tables in DB
Basic Data Access
• Once you’ve created a model, Django automatically provides a high-
level Python API for working with those models.
• Try it out by running “python manage.py shell” and typing the
following:
• Creating an Object:
• Import the appropriate model class and instantiate it with values for each
field:
• p2 = Publisher(name='O\'Reilly Media', address='10 Fawcett St.', city='Cambridge',
state_province='MA', country='U.S.A.', website='http://www.oreilly.com/')
• Saving the Object to the Database:
• p2.save()
• Django executes an SQL INSERT statement behind the scenes to add the
object to the database.
Retrieving Objects from the
Database
• Use the model’s objects attribute to fetch objects from the database:
• publisher_list = Publisher.objects.all()
• Django executes an SQL SELECT statement behind the scenes to
retrieve all Publisher objects.
• Print publisher_list:
• >>> publisher_list
• [<Publisher: Publisher object>, <Publisher: Publisher object>]
• These few lines of code accomplish quite a bit. Here are the
highlights:
• To create an object, just import the appropriate model class and instantiate it
by passing in values for each field.
• To save the object to the database, call the save() method on the object.
Behind the scenes, Django executes an SQL INSERT statement here.
• To retrieve objects from the database, use the attribute Publisher.objects.
Fetch a list of all Publisher objects in the database with the statement
Publisher.objects.all().
• Behind the scenes, Django executes an SQL SELECT statement here.
Adding Model String
Representations
INSERT INTO book_publisher
(name, address, city, state_province, country, website)
VALUES ('Apress', '2855 Telegraph Ave.', 'Berkeley', 'CA', 'U.S.A.',
'http://www.apress.com/');
Retrieving Single Objects
Ordering Data
Chaining Lookups & Slicing Data
Deleting Objects
Making Changes to a Database
Schema
Making Changes to a Database
Schema

You might also like