Built-in Django filters

Django filters are designed to format template variables. The syntax to apply Django filters is the vertical bar character | also known as 'pipe' in Unix environments (e.g.{{variable|filter}}). It's worth mentioning that it's possible to use multiple filters on the same variable (e.g.{{variable|filter|filter}}).

I'll classify each built-in Django filter into functional sections so it's easier to identify them. The functional classes I'll use are: Dates, Strings, Lists, Numbers, Dictionaries, Spacing and special characters, Development and Testing & Urls.

Tip You can apply Django filters to entire sections with the {% filter %} tag. If you have a group of variables in the same section and want to apply the same filter to all of them, it's easier to use the {% filter %} tag than to individually declare the filter on each variable. The next section in this chapter on Django built-in tags provides more details on the {% filter %} tag

Dates

Tip If you provide no string argument to the date filter (e.g. {{variable|date}}), it defaults to the "N j, Y" string which comes from the default value of DATE_FORMAT.

Note The date filter can also accept predefined date variables {{variable|date:"DATE_FORMAT"}}, {{variable|date:"DATETIME_FORMAT"}}, {{variable|date:"SHORT_DATE_FORMAT" %} or {{variable|date:"SHORT_DATETIME_FORMAT"}}.

The predefined date variables in themselves are also composed of date strings based on the syntax in table 3-3. For example DATE_FORMAT default's to "N j, Y" (e.g. Jan 1, 2018), DATETIME_FORMAT defaults to "N j, Y, P" (e.g. Jan 1, 2018, 12 a.m.), SHORT_DATE_FORMAT defaults to "m/d/Y" (e.g. 01/01/2018) and SHORT_DATETIME_FORMAT defaults to "m/d/Y P" (e.g. 01/01/2018 12 a.m.). Each date variable can be overridden with different date strings in a project's settings.py file.

Table 3-3. Django date & time format characters
Standards based characters Description
c Outputs ISO 8601 format (e.g. 2015-01-02T10:30:00.000123+02:00 or 2015-01-02T10:30:00.000123 if the datetime has no timezone [i.e.naive datetime])
r Outputs RFC 2822 formatted date (e.g.'Thu, 21 Dec 2000 16:01:07 +0200')
U Outputs seconds since Unix epoch date--January 1 1970 00:00:00 UTC
I (Uppercase i) Outputs whether daylight savings time is in effect (e.g.'1' or '0')
Hour based characters Description
a Outputs 'a.m.' or 'p.m.'
A Outputs 'AM' or 'PM'
f Outputs time, 12-hour hours and minutes, with minutes left off if they're zero (e.g.'1', '1:30')
g Outputs hour, 12-hour format without leading zeros (e.g.'1' to '12')
G Outputs hour, 24-hour format without leading zeros (e.g.'0' to '23')
h Outputs hour, 12-hour format (e.g.'01' to '12')
H Outputs hour, 24-hour format (e.g.'00' to '23')
i Outputs minutes (e.g.'00' to '59')
P Outputs time, 12-hour hours, minutes and 'a.m.'/'p.m.', with minutes left off if they're zero and the special-case strings 'midnight' and 'noon' if appropriate (e.g.'1 a.m.', '1:30 p.m.', 'midnight', 'noon', '12:30 p.m.')
s Outputs seconds, 2 digits with leading zeros (e.g.'00' to '59')
u Outputs microseconds (e.g.000000 to 999999)
Timezone characters Description
e Outputs timezone name. Can be in any format, or might return an empty string, depending datetime definition (e.g. '', 'GMT', '-500', 'US/Eastern')
O Outputs difference in timezone to Greenwich time in hours (e.g.'+0200')
T Outputs datetime time zone (e.g.'EST', 'MDT')
Z Outputs time zone offset in seconds. The offset for timezones west of UTC is always negative, and for those east of UTC is always positive (e.g.-43200 to 43200)
Day and week characters Description
D Outputs day of the week, textual, 3 letters (e.g.'Thu','Fri')
l (Lowercase L) Outputs day of the week, textual, long (e.g.'Thursday','Friday')
S Outputs English ordinal suffix for day of the month, 2 characters (e.g.'st', 'nd', 'rd' or 'th')
w Outputs day of the week, digits without leading zeros (e.g.'0' for Sunday to '6' for Saturday)
z Outputs day of the year (e.g.0 to 365)
W Outputs the week number of the year, with weeks starting on Monday based on ISO-8601 (e.g.1, 53)
o Outputs week-numbering year, corresponding to the ISO-8601 week number (W)(e.g.'1999')
Month characters Description
b Outputs textual month, 3 letters, lowercase (e.g.'jan','feb')
d Outputs day of the month, 2 digits with leading zeros (e.g.'01' to '31')
j Outputs day of the month without leading zeros (e.g. '1' to '31')
E Outputs month, locale specific alternative representation usually used for long date representation (e.g. 'listopada' for Polish locale, as opposed to 'Listopad')
F Outputs month, textual, long (e.g. 'January','February')
m Outputs month, 2 digits with leading zeros (e.g.'01' to '12')
M Outputs month, textual, 3 letters (e.g.'Jan','Feb')
n Outputs month without leading zeros (e.g.'1' to '12')
N Outputs month abbreviation in Associated Press style (e.g.'Jan', 'Feb', 'March', 'May')
t Outputs number of days in the given month (e.g. 28 to 31)
Year characters Description
L Outputs boolean for whether it's a leap year (e.g.True or False)
y Outputs year, 2 digits (e.g.'99')
Y Outputs year, 4 digits (e.g.'1999')

To literally output a date character in a string statement you can use the backslash character (e.g. {{variable|date:"jS \o\f F o"}} outputs 1st of January 2018, note the escaped \o\f)

Tip If you provide no string argument to the date filter (e.g. {{variable|time}}), it defaults to the "P" string which comes from the default value of TIME_FORMAT.Note The time filter can also accept predefined a time variable {{variable|date:"TIME FORMAT"}.The predefined time is also composed of a time string based on the syntax in table 3-3. For example, TIME_FORMAT default's to "P" (e.g. 4 a.m.) and this can be overridden defining TIME_FORMAT in a project's settings.py file.

Strings, lists and numbers

Numbers

Strings

Listing 3-15 Django linenumbers filter

# Variable definition 
Downtown
Uptown
Midtown
# Template definition with linenumbers filter
{{variable|linenumbers}}
# Output
1.Downtown
2.Uptown
3.Midtown

Lists and dictionaries

Spacing and special characters

  • addslashes.- The addslashes filter adds slashes to all quotes (i.e. it escapes quotes). The addslashes filter is useful when Django templates are used to export data to other systems that require to escape quotes (e.g. CSV files). For example, if a variable contains Today's news the filter statement {{variable|addslashes}} outputs Today\'s news.
  • center.- The center filter center aligns a value and pads it with additional white space characters until it reaches the given argument of characters. For example, if a variable contains mocha the filter statement {{variable|center:"15"}} outputs
  • " mocha ". (i.e. 5 spaces to the left of mocha, 5 spaces for mocha, 5 spaces to the right of mocha.
  • ljust.- The ljust filter left aligns a value and pads it with additional white space characters until it reaches the given argument of characters. For example, if a variable contains mocha the filter statement {{variable|ljust:"15"}} outputs
  • "mocha ".(i.e. 5 spaces for mocha, 10 space padding).
  • rjust.- The rjust filter right aligns a value and pads it with additional white space characters until it reaches the given argument of characters. For example, if a variable contains latte the filter statement {{variable|rjust:"10"}} outputs
  • " latte"."(i.e. 5 space padding, 5 spaces for latte).
  • escape.- The escape filter escapes HTML characters from a value. Specifically with the escape filter: < is converted to &lt; ,> is converted to &gt; ,' (single quote) is converted to &#39; ," (double quote) is converted to &quot; and & is converted to &amp.
  • Tip If you use the escape filter on contiguous variables, it's easier to wrap the variables with the {% autoescape %} tag to achieve the same results.
  • escapejs.- The escapejs filter escapes characters into unicode strings which are often used for JavaScript strings. Though the escapejs filter does not make a string HTML safe, it does protect against syntax errors when using templates to generate JavaScript/JSON. For example, if a variable contains "mocha\r\n \'price:2.25" the filter statement {{variable|escapejs}} outputs \u0022mocha\u000D\u000A \u0027price:2.25\u0022.
  • force_escape.- The force_escape filter escapes HTML characters from a value just like the escape filter. The difference is force_escape is applied immediately and returns a new and escaped string. This is useful when you need multiple escaping or want to apply other filters to the escaped results. Normally, you'll use the escape filter.
  • linebreaks.- The linebreaks filter replaces plain text line breaks with HTML tags, a single newline becomes an HTML line break (<br/>) and a new line followed by a blank line becomes a paragraph break (</p>). For example, if a variable contains 385 Main\nSan Diego, CA the filter statement {{variable|linebreaks}} outputs <p>385 Main<br/>San Diego, CA</p>.
  • linebreaksbr.- The linebreaksbr filter converts all text variable new lines to HTML line breaks (<br/>). For example, if a variable contains 385 Main\nSan Diego, CA the filter statement {{variable|linebreaksbr}} outputs 385 Main<br/>San Diego, CA.
  • striptags.- The striptags filter removes all HTML tags from a value. For example, if a variable contains <b>Coffee</b>house, the <i>best</i> <span>drinks</span> the filter statement {{variable|striptags}} outputs Coffeehouse, the best drinks.
  • Caution The striptags filter uses very basic logic to strip HTML tags. This means there's a possibility a convoluted piece of HTML isn't fully stripped of tags. This is why content in variables passed through the striptags filter is automatically escaped and should never be marked as safe.
  • safe.- The safe filter marks a string as not requiring HTML escaping.
  • safeseq.- The safeseq applies the safe filter to each element of a list. It's useful in conjunction with other filters that operate on a list, such as the join filter (e.g.{{stores|safeseq|join:", "}}). You wouldn't use the safe filter directly on list variables, as it would first convert the variable to a string, rather than working with the individual elements of a list.
  • wordwrap.- The wordwrap filter wraps words at a given character line length argument. Listing 3-17 illustrates an example of the wordwrap filter.
  • Listing 3-17. Django wordwrap filter

    # Variable definition 
    Coffeehouse started as a small store
    # Template definition with wordwrap filter for every 12 characters
    {{variable|wordwrap:12}}
    # Output
    Coffeehouse 
    started as a
    small store
    

    Development and testing

  • pprint.- The pprint filter is a wrapper for Python's pprint.pprint(). The pprint filter is useful during development and testing because it outputs the formatted representation of an object.
  • Urls

  • iriencode.- The iriencode filter converts an Internationalized Resource Identifier (IRI) to a string that is suitable for inclusion in a URL. This is necessary if you're trying to use strings containing non-ASCII characters in a URL. For example, if a variable contains ?type=cold&size=large the filter statement {{variable|iriencode}} outputs ?type=cold&amp;size=large.
  • urlencode.- The urlencode filter escapes a value for use in a URL. For example, if a variable contains http://localhost/drinks?type=cold&size=large the filter statement {{variable|urlencode}} outputs http%3A//localhost/drinks%3Ftype%3Dcold%26size%3Dlarge. The urlenconde filter assumes the / character is safe. The urlencode filter can accept an optional argument with the characters that should not be escaped. An empty string can be provided when all characters should be escaped (e.g.{{variable|urlencode:""}} outputs http%3A%2F%2Flocalhost%2Fdrinks%3Ftype%3Dcold%26size%3Dlarge).
  • urlize.- The urlize filter converts text URLs or email addresses into clickable HTML links. This urlize filter works on links prefixed with http://, https://, or www.. Links generated by the urlize filter have a rel="nofollow" attribute added to them. For example, if a variable contains Visit http://localhost/drinks the filter statement {{variable|urlize}} outputs Visit <a href="http://localhost/drinks" rel="nofollow">http://localhost/drinks</a>; if a variables contains Contact support@coffeehouse.com the filter statement {{variable|urlize}} outputs Contact <a href="mailto:support@coffeehouse.com">support@coffeehouse.com</a>.
  • urlizetrunc.- The urlizetrunc filter converts text URLs and emails into clickable HTML links -- just like the urlize filter -- except it truncates the url to a given number of characters that include an ellipsis sequence. For example, if a variable contains Visit http://localhost/drinks the filter statement {{variable|urlizetrunc:20}} outputs Visit <a href="http://localhost/drinks" rel="nofollow">http://localhost/...</a>.
  • Caution The urlize and urlizetrunc filters should only be applied to variables with plain text. If applied to variables with HTML links the filter logic won't work as expected.
    1. https://docs.python.org/3/library/stdtypes.html#old-string-formatting