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 filters


add

Adds the argument to the value. For example:

{{ value|add:"2" }} 

If value is 4, then the output will be 6.

addslashes

Adds slashes before quotes. Useful for escaping strings in CSV, for example. For example:

{{ value|addslashes }} 

If value is I'm using Django, the output will be I'm using Django.

capfirst

Capitalizes the first character of the value. If the first character is not a letter, this filter has no effect.

center

Centers the value in a field of a given width. For example:

"{{ value|center:"14" }}" 

If value is Django, the output will be  Django.

cut

Removes all values of arg from the given string.

date

Formats a date according to the given format. Uses a similar format as PHP's date() function with some differences.

Note

These format characters are not used in Django outside of templates. They were designed to be compatible with PHP to ease transitioning for designers. For a full list of format strings see the Django Project website at https://docs.djangoproject.com/en/dev/ref/templates/builtins/#date.

For example:

{{ value|date:"D d M Y" }} 

If value is a datetime object (for example, the result of datetime.datetime.now()), the output will be the string Fri 01 Jul 2016. The format passed can be one of the predefined ones DATE_FORMAT, DATETIME_FORMAT, SHORT_DATE_FORMAT, or SHORT_DATETIME_FORMAT, or a custom format that uses date format specifiers.

default

If value evaluates to False, uses the given default. Otherwise, uses the value. For example:

{{ value|default:"nothing" }}     

default_if_none

If (and only if) value is None, uses the given default. Otherwise, uses the value.

dictsort

Takes a list of dictionaries and returns that list sorted by the key given in the argument. For example:

{{ value|dictsort:"name" }} 

dictsortreversed

Takes a list of dictionaries and returns that list sorted in reverse order by the key given in the argument.

divisibleby

Returns True if the value is divisible by the argument. For example:

{{ value|divisibleby:"3" }} 

If value is 21, the output would be True.

escape

Escapes a string's HTML. Specifically, it makes these replacements:

  • < is converted to &lt;
  • > is converted to &gt;
  • ' (single quote) is converted to '
  • " (double quote) is converted to &quot;
  • & is converted to &amp;

The escaping is only applied when the string is output, so it does not matter where in a chained sequence of filters you put escape: it will always be applied as though it were the last filter.

escapejs

Escapes characters for use in JavaScript strings. This does not make the string safe for use in HTML, but does protect you from syntax errors when using templates to generate JavaScript/JSON.

filesizeformat

Formats the value like a 'human-readable' file size (that is, '13 KB', '4.1 MB', '102 bytes', and more). For example:

{{ value|filesizeformat }} 

If value is 123456789, the output would be 117.7 MB.

first

Returns the first item in a list.

floatformat

When used without an argument, rounds a floating-point number to one decimal place-but only if there's a decimal part to be displayed. If used with a numeric integer argument, floatformat rounds a number to that many decimal places.

For example, if value is 34.23234, {{ value|floatformat:3 }} will output 34.232.

get_digit

Given a whole number, returns the requested digit, where 1 is the right-most digit.

iriencode

Converts an Internationalized Resource Identifier (IRI) to a string that is suitable for including in a URL.

join

Joins a list with a string, like Python's str.join(list).

last

Returns the last item in a list.

length

Returns the length of the value. This works for both strings and lists.

length_is

Returns True if the value's length is the argument, or False otherwise. For example:

{{ value|length_is:"4" }} 

linebreaks

Replaces line breaks in plain text with appropriate HTML; a single newline becomes an HTML line break (<br />) and a new line followed by a blank line becomes a paragraph break (</p>).

linebreaksbr

Converts all newlines in a piece of plain text to HTML line breaks (<br />).

linenumbers

Displays text with line numbers.

ljust

Left-aligns the value in a field of a given width. For example:

{{ value|ljust:"10" }} 

If value is Django, the output will be Django.

lower

Converts a string into all lowercase.

make_list

Returns the value turned into a list. For a string, it's a list of characters. For an integer, the argument is cast into an Unicode string before creating a list.

phone2numeric

Converts a phone number (possibly containing letters) to its numerical equivalent. The input doesn't have to be a valid phone number. This will happily convert any string. For example:

{{ value|phone2numeric }} 

If value is 800-COLLECT, the output will be 800-2655328.

pluralize

Returns a plural suffix if the value is not 1. By default, this suffix is s.

For words that don't pluralize by simple suffix, you can specify both a singular and plural suffix, separated by a comma. Example:

You have {{ num_cherries }} cherr{{ num_cherries|pluralize:"y,ies" }}. 

pprint

A wrapper around pprint.pprint()--for debugging.

random

Returns a random item from the given list.

rjust

Right-aligns the value in a field of a given width. For example:

{{ value|rjust:"10" }} 

If value is Django, the output will be  Django.

safe

Marks a string as not requiring further HTML escaping prior to output. When autoescaping is off, this filter has no effect.

safeseq

Applies the safe filter to each element of a sequence. Useful in conjunction with other filters that operate on sequences, such as join. For example:

{{ some_list|safeseq|join:", " }} 

You couldn't use the safe filter directly in this case, as it would first convert the variable into a string, rather than working with the individual elements of the sequence.

slice

Returns a slice of the list. Uses the same syntax as Python's list slicing.

slugify

Converts to ASCII. Converts spaces to hyphens. Removes characters that aren't alphanumeric, underscores, or hyphens. Converts to lowercase. Also strips leading and trailing whitespace.

stringformat

Formats the variable according to the argument, a string formatting specifier. This specifier uses Python string formatting syntax, with the exception that the leading % is dropped.

striptags

Makes all possible efforts to strip all [X]HTML tags. For example:

{{ value|striptags }} 

time

Formats a time according to the given format. Given format can be the predefined one TIME_FORMAT, or a custom format, same as the date filter.

timesince

Formats a date as the time since that date (for example, 4 days, 6 hours). Takes an optional argument that is a variable containing the date to use as the comparison point (without the argument, the comparison point is now).

timeuntil

Measures the time from now until the given date or datetime.

title

Converts a string into title case by making words start with an uppercase character and the remaining characters lowercase.

truncatechars

Truncates a string if it is longer than the specified number of characters. Truncated strings will end with a translatable ellipsis sequence (...). For example:

{{ value|truncatechars:9 }} 

truncatechars_html

Similar to truncatechars, except that it is aware of HTML tags.

truncatewords

Truncates a string after a certain number of words.

truncatewords_html

Similar to truncatewords, except that it is aware of HTML tags.

unordered_list

Recursively takes a self-nested list and returns an HTML unordered list-without opening and closing tags.

upper

Converts a string into all uppercase.

urlencode

Escapes a value for use in a URL.

urlize

Converts URLs and email addresses in text into clickable links. This template tag works on links prefixed with http://, https://, or www..

urlizetrunc

Converts URLs and email addresses into clickable links just like urlize, but truncates URLs longer than the given character limit. For example:

{{ value|urlizetrunc:15 }} 

If value is Check out www.djangoproject.com, the output would be Check out <a href="http://www.djangoproject.com" rel="nofollow">www.djangopr...</a>. As with urlize, this filter should only be applied to plain text.

wordcount

Returns the number of words.

wordwrap

Wraps words at specified line length.

yesno

Maps values for true, false and (optionally) None, to the strings yes, no, maybe, or a custom mapping passed as a comma-separated list, and returns one of those strings according to the value: For example:

{{ value|yesno:"yeah,no,maybe" }}