tag (templates)

archive

accessing the object inside a django admin change_form.html template Jul
06
1
2

When overriding the change_form.html template sometimes I need access to the object that is being edited. The change_view method provides the original object in the 'original' context variable.

You can access the object in the template using the original variable:

{{ original }}

comments

iterate over a dictionary inside a django template Apr
27
1
0

The official Django documents how to iterate over a dictionary inside a for loop, but I sometimes forget. I'll attempt to do something like this:

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

but will fail miserably. The key to extracting a dictionary inside django templates is the items dictionary function, which "Return a copy of the dictionary’s list of (key, value) pairs".

This allows us to loop through the dictionary using items like so:

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

comments

convert integer to string inside a django template Mar
15
1
0

Every now and then I come across a situation where I'm required to do an integer to string comparison inside a Django template. I need to unify the data types before I run the comparison or else the equality will fail. This sounds like a job for template filters.

I could write my own int_to_string filter like the following (the @stringfilter converts the argument to a string before it passes the variable into the function).

from django.template.defaultfilters import stringfilter

@register.filter
@stringfilter
def int_to_string(value):
    return value

However, I would then have to load the filters into the necessary templates. Yes, I know it's not hard to do, but I'm lazy. Wouldn't it be nice if there was a pre-built filter that did the conversion for me? Well I'm in luck because the slugify filter does just that.

All I need to do is slugify the integer and compare it to the string variable. It works like a charm because when using slugify on an integer, besides the int to string conversion, it won't transform the data.

{% ifequal my_integer|slugify my_string %}

comments