Serafeim
Serafeim

Reputation: 15084

Django template check for empty when I have an if inside a for

I have the following code in my template:

{% for req in user.requests_made_set.all %}
  {% if not req.is_published %}
    {{ req }}
  {% endif %}
{% empty %}
  No requests
{% endfor %}

If there are some requests but none has the is_published = True then how could I output a message (like "No requests") ?? I'd only like to use Django templates and not do it in my view!

Thanks

Upvotes: 1

Views: 3750

Answers (1)

koniiiik
koniiiik

Reputation: 4382

Even if this might be possible to achieve in the template, I (and probably many other people) would advise against it. To achieve this, you basically need to find out whether there are any objects in the database matching some criteria. That is certainly not something that belongs into a template.

Templates are intended to be used to define how stuff is displayed. The task you're solving is determining what stuff to display. This definitely belongs in a view and not a template.

If you want to avoid placing it in a view just because you want the information to appear on each page, regardless of the view, consider using a context processor which would add the required information to your template context automatically, or writing a template tag that would solve this for you.

Upvotes: 6

Related Questions