Book Image

Mastering Django: Core

By : Nigel George
Book Image

Mastering Django: Core

By: Nigel George

Overview of this book

Mastering Django: Core is a completely revised and updated version of the original Django Book, written by Adrian Holovaty and Jacob Kaplan-Moss - the creators of Django. The main goal of this book is to make you a Django expert. By reading this book, you’ll learn the skills needed to develop powerful websites quickly, with code that is clean and easy to maintain. This book is also a programmer’s manual that provides complete coverage of the current Long Term Support (LTS) version of Django. For developers creating applications for commercial and business critical deployments, Mastering Django: Core provides a complete, up-to-date resource for Django 1.8LTS with a stable code-base, security fixes and support out to 2018.
Table of Contents (33 chapters)
Mastering Django: Core
Credits
About the Author
www.PacktPub.com
Preface
Free Chapter
1
Introduction to Django and Getting Started

Built-in tags


autoescape

Controls the current auto-escaping behavior. This tag takes either on or off as an argument and that determines whether auto-escaping is in effect inside the block. The block is closed with an endautoescape ending tag.

When auto-escaping is in effect, all variable content has HTML escaping applied to it before placing the result into the output (but after any filters have been applied). This is equivalent to manually applying the escape filter to each variable.

The only exceptions are variables that are already marked as safe from escaping, either by the code that populated the variable, or because it has had the safe or escape filters applied. Sample usage:

{% autoescape on %} 
    {{ body }} 
{% endautoescape %} 

block

Defines a block that can be overridden by child templates. See "template inheritance" in Chapter 3, Templates, for more information.

comment

Ignores everything between {% comment %} and {% endcomment %}. An optional note may be inserted in the first tag. For example, this is useful when commenting out code for documenting why the code was disabled.

Comment tags cannot be nested.

csrf_token

This tag is used for CSRF protection. For more information on Cross Site Request Forgeries (CSRF) see Chapter 3, Templates, and Chapter 19, Security in Django.

cycle

Produces one of its arguments each time this tag is encountered. The first argument is produced on the first encounter, the second argument on the second encounter, and so forth. Once all arguments are exhausted, the tag cycles to the first argument and produces it again. This tag is particularly useful in a loop:

{% for o in some_list %} 
    <tr class="{% cycle 'row1' 'row2' %}"> 
        ... 
    </tr> 
{% endfor %} 

The first iteration produces HTML that refers to class row1, the second to row2, the third to row1 again, and so on for each iteration of the loop. You can use variables, too. For example, if you have two template variables, rowvalue1 and rowvalue2, you can alternate between their values like this:

{% for o in some_list %} 
    <tr class="{% cycle rowvalue1 rowvalue2 %}"> 
        ... 
    </tr> 
{% endfor %} 

You can also mix variables and strings:

{% for o in some_list %} 
    <tr class="{% cycle 'row1' rowvalue2 'row3' %}"> 
        ... 
    </tr> 
{% endfor %} 

You can use any number of values in a cycle tag, separated by spaces. Values enclosed in single quotes (') or double quotes (") are treated as string literals, while values without quotes are treated as template variables.

debug

Outputs a whole load of debugging information, including the current context and imported modules.

extends

Signals that this template extends a parent template. This tag can be used in two ways:

  • {% extends "base.html" %} (with quotes) uses the literal value "base.html" as the name of the parent template to extend.
  • {% extends variable %} uses the value of variable. If the variable evaluates to a string, Django will use that string as the name of the parent template. If the variable evaluates to a Template object, Django will use that object as the parent template.

filter

Filters the contents of the block through one or more filters. See the Built-in Filters section later in this appendix for a list of filters in Django.

firstof

Outputs the first argument variable that is not False. Outputs nothing if all the passed variables are False. Sample usage:

{% firstof var1 var2 var3 %} 

This is equivalent to:

{% if var1 %} 
    {{ var1 }} 
{% elif var2 %} 
    {{ var2 }} 
{% elif var3 %} 
    {{ var3 }} 
{% endif %} 

for

Loops over each item in an array, making the item available in a context variable. For example, to display a list of athletes provided in athlete_list:

<ul> 
{% for athlete in athlete_list %} 
    <li>{{ athlete.name }}</li> 
{% endfor %} 
</ul> 

You can loop over a list in reverse by using {% for obj in list reversed %}. If you need to loop over a list of lists, you can unpack the values in each sub list into individual variables. This can also be useful if you need to access the items in a dictionary. For example, if your context contained a dictionary data, the following would display the keys and values of the dictionary:

{% for key, value in data.items %} 
    {{ key }}: {{ value }} 
{% endfor %} 

for... empty

The for tag can take an optional {% empty %} clause whose text is displayed if the given array is empty or could not be found:

<ul> 
{% for athlete in athlete_list %} 
    <li>{{ athlete.name }}</li> 
{% empty %} 
    <li>Sorry, no athletes in this list.</li> 
{% endfor %} 
</ul> 

if

The {% if %} tag evaluates a variable, and if that variable is true (that is, exists, is not empty, and is not a false boolean value) the contents of the block are output:

{% if athlete_list %} 
    Number of athletes: {{ athlete_list|length }} 
{% elif athlete_in_locker_room_list %} 
    Athletes should be out of the locker room soon! 
{% else %} 
    No athletes. 
{% endif %} 

In the above, if athlete_list is not empty, the number of athletes will be displayed by the {{ athlete_list|length }} variable. As you can see, the if tag may take one or several {% elif %} clauses, as well as an {% else %} clause that will be displayed if all previous conditions fail. These clauses are optional.

Boolean operators

if tags may use and, or, or not to test a number of variables or to negate a given variable:

{% if athlete_list and coach_list %} 
    Both athletes and coaches are available. 
{% endif %} 
 
{% if not athlete_list %} 
    There are no athletes. 
{% endif %} 
 
{% if athlete_list or coach_list %} 
    There are some athletes or some coaches. 
{% endif %} 

Use of both and and or clauses within the same tag is allowed, with and having higher precedence than or for example:

{% if athlete_list and coach_list or cheerleader_list %} 

will be interpreted like:

if (athlete_list and coach_list) or cheerleader_list 

Use of actual parentheses in the if tag is invalid syntax. If you need them to indicate precedence, you should use nested if tags.

if tags may also use the operators ==, !=, <, >, <=, >=, and in which work as listed in Table E.1.

Operator

Example

==

{% if somevar == "x" %} ...

!=

{% if somevar != "x" %} ...

<

{% if somevar < 100 %} ...

>

{% if somevar > 10 %} ...

<=

{% if somevar <= 100 %} ...

>=

{% if somevar >= 10 %} ...

In

{% if "bc" in "abcdef" %}

Table E.1: Boolean operators in template tags

Complex expressions

All of the above can be combined to form complex expressions. For such expressions, it can be important to know how the operators are grouped when the expression is evaluated-that is, the precedence rules. The precedence of the operators, from lowest to highest, is as follows:

  • or
  • and
  • not
  • in
  • ==, !=, <, >, <=, and >=

This order of precedence follows Python exactly.

Filters

You can also use filters in the if expression. For example:

{% if messages|length >= 100 %} 
   You have lots of messages today! 
{% endif %} 

ifchanged

Check if a value has changed from the last iteration of a loop. The

{% ifchanged %} block tag is used within a loop. It has two possible uses:

  • Checks its own rendered contents against its previous state and only displays the content if it has changed
  • If given one or more variables, check whether any variable has changed

ifequal

Output the contents of the block if the two arguments equal each other. Example:

{% ifequal user.pk comment.user_id %} 
    ... 
{% endifequal %} 

An alternative to the ifequal tag is to use the if tag and the == operator.

ifnotequal

Just like ifequal, except it tests that the two arguments are not equal. An alternative to the ifnotequal tag is to use the if tag and the != operator.

include

Loads a template and renders it with the current context. This is a way of including other templates within a template. The template name can either be a variable:

{% include template_name %} 

or a hard-coded (quoted) string:

{% include "foo/bar.html" %} 

load

Loads a custom template tag set. For example, the following template would load all the tags and filters registered in somelibrary and otherlibrary located in package package:

{% load somelibrary package.otherlibrary %} 

You can also selectively load individual filters or tags from a library, using the from argument.

In this example, the template tags/filters named foo and bar will be loaded from somelibrary:

{% load foo bar from somelibrary %} 

See Custom tag and Filter libraries for more information.

lorem

Displays random lorem ipsum Latin text. This is useful for providing sample data in templates. Usage:

{% lorem [count] [method] [random] %} 

The {% lorem %} tag can be used with zero, one, two or three arguments. The arguments are:

  • Count: A number (or variable) containing the number of paragraphs or words to generate (default is 1).
  • Method: Either w for words, p for HTML paragraphs or b for plain-text paragraph blocks (default is b).
  • Random: The word random, which if given, does not use the common paragraph (Lorem ipsum dolor sit amet...) when generating text.

For example, {% lorem 2 w random %} will output two random Latin words.

now

Displays the current date and/or time, using a format according to the given string. Such string can contain format specifiers characters as described in the date filter section. Example:

It is {% now "jS F Y H:i" %} 

The format passed can also be one of the predefined ones DATE_FORMAT, DATETIME_FORMAT, SHORT_DATE_FORMAT, or SHORT_DATETIME_FORMAT. The predefined formats may vary depending on the current locale and if format-localization is enabled, for example:

It is {% now "SHORT_DATETIME_FORMAT" %} 

regroup

Regroups a list of alike objects by a common attribute.

{% regroup %} produces a list of group objects. Each group object has two attributes:

  • grouper: The item that was grouped by (for example, the string India or Japan)
  • list: A list of all items in this group (for example, a list of all cities with country = "India")

Note that {% regroup %} does not order its input!

Any valid template lookup is a legal grouping attribute for the regroup tag, including methods, attributes, dictionary keys, and list items.

spaceless

Removes whitespace between HTML tags. This includes tab characters and newlines. Example usage:

{% spaceless %} 
    <p> 
        <a href="foo/">Foo</a> 
    </p> 
{% endspaceless %} 

This example would return this HTML:

<p><a href="foo/">Foo</a></p> 

templatetag

Outputs one of the syntax characters used to compose template tags. Since the template system has no concept of escaping, to display one of the bits used in template tags, you must use the {% templatetag %} tag. The argument tells which template bit to output:

  • openblock outputs: {%
  • closeblock outputs: %}
  • openvariable outputs: {{
  • closevariable outputs: }}
  • openbrace outputs: {
  • closebrace outputs: }
  • opencomment outputs: {#
  • closecomment outputs: #}

Sample usage:

{% templatetag openblock %} url 'entry_list' {% templatetag closeblock %} 

url

Returns an absolute path reference (a URL without the domain name) matching a given view function and optional parameters. Any special characters in the resulting path will be encoded using iri_to_uri(). This is a way to output links without violating the DRY principle by having to hard-code URLs in your templates:

{% url 'some-url-name' v1 v2 %} 

The first argument is a path to a view function in the format package.package.module.function. It can be a quoted literal or any other context variable. Additional arguments are optional and should be space-separated values that will be used as arguments in the URL.

verbatim

Stops the template engine from rendering the contents of this block tag. A common use is to allow a Javascript template layer that collides with Django's syntax.

widthratio

For creating bar charts and such, this tag calculates the ratio of a given value to a maximum value, and then applies that ratio to a constant. For example:

<img src="bar.png" alt="Bar" 
     height="10" width="{% widthratio this_value max_value max_width %}" /> 

with

Caches a complex variable under a simpler name. This is useful when accessing an expensive method (for example, one that hits the database) multiple times. For example:

{% with total=business.employees.count %} 
    {{ total }} employee{{ total|pluralize }} 
{% endwith %}