1

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

Serafeim
  • 14,962
  • 14
  • 91
  • 133

1 Answers1

6

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.

koniiiik
  • 4,240
  • 1
  • 23
  • 28
  • Ok probably I'll create a template tag. I just thought that this should've been possible since django already has the {% empty %} tag... – Serafeim Apr 21 '12 at 07:01
  • 1
    Yeah, only that `{% empty %}` checks whether an iterable object in the context is empty or not. Not a filtered subset of it. Also, the code is suboptimal. Imagine `requests_made_set` contains thousands of requests and only a handful of them are published. You iterate over all of them when, in fact, you only want a subset. You definitely want to filter this at database level. – koniiiik Apr 21 '12 at 07:29
  • Probably you are right. Quick question: If I create a template filter named only_published that accepts a queryset (the user.requests_made_set.all queryset) and use that to filter the request {% for req in user.requests_made_set.all|only_published %} will to work ? Also, will only the published requests be shown (lazy evaluation) if I use that ? Thanks ! – Serafeim Apr 21 '12 at 17:24