Templates

Relative imports and extends in templates

Django templates can not import via relative imports. This is therefore wrong.:

{% extends '../base.html' %}

{% include '../../breadcrumbs_frag.html' %}

Solution: Always import as specified from the application/template directory, or the TEMPLATE_DIRS specified in settings.py

Not wrapping {% for %} in {% if %}

A common pattern is:

<ul><!-- or any other element, eg table -->
{% for comments in post.comment_set.all %}
<li>
{{ comment }}
</li>
{% endfor %}
</ul>

This doesnot handle an empty queryset, and will create a empty <ul></ul>, which might be visible and break your design depending on your css.

Solution:

Wrap it in {% if %}:

{% if post.comment_set.all %}
<ul><!-- or any other element, eg table -->
{% for comments in post.comment_set.all %}
<li>
{{ comment }}
</li>
{% endfor %}
</ul>
{# optional else #}
{% else %}
<div>No comment</div>
{% endif %}

Or (Django 1.1 only)

<ul><!– or any other element, eg table –> {% for comments in post.comment_set.all %} <li> {{ comment }} </li> {% empty %} <li> No comment </li> {% endfor %} </ul>

Template Silencing:

Any empty variable is rendered empty in the templates. But errors are rendered empty as well. Django templates silence many variable errors and render nothing at that position.

Solution:

During development set the template string to a convenient value when the template string is invalid.

This setting helps.:

TEMPLATE_STRING_IF_INVALID = ‘{{ %s }}’

Tip: This should be one of the settings in your localsettings, or one of conditions within if DEBUG:

Warning: The breaks the admin design.