in deep of django framework
in deep of django framework
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.
• Reversed Loop
• Add reversed to loop in reverse order:
• Nesting for Tags
• Example of nested loops:
• 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 &
• < to <
• > to >
• " to "
• ' to '
• 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.
• 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:
• 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