How to display text if the field is empty? - templates

How to display a text if the field is empty ?
I tried the following code but it does not work :
{% if content.field_description is not empty %}
{{ content.field_description }}
{% else %}
test
{% endif %}

If you have Twig Tweak installed, you can do the following:
{% if content['field_description'] | field_value != '' %}
{{ content['field_description'].value | striptags }}
{% else %}
<p class="des-empty">test</p>
{% endif %}

When field is empty it is not coming with content variable
so you can simply check by isset
{% if content.field_description %}
{{ content.field_description }}
{% else %}
<p class="des-empty">test</p>
{% endif %}

The below worked for me:
{% if content['field_description'] IS NOT EMPTY %}
{{ content['field_description'].value | striptags }}
{% else %}
<p class="des-empty">test</p>
{% endif %}
Please note that it may vary based on the content type and fields you are dealing with.

Related

Error during template rendering / Could not parse some characters

Im trying to get a bio info for each profile, when running server and going to accounts/profile y find this error:
Could not parse some characters: |% with website=profile.website| | default:"" %
{% extends 'base.html' %}
{% block title %}Profile{% endblock %}
{% block content %}
<h1>
{{ user.get_null_name }} (#{{ user.username }})
</h1>
{% with profile=user.profile %}
{% if profile %}
<h2>
{{ profile.persona }}
</h2>
<div>
{{ profile.bio|default:"" }}
</div>
<div>
{{ % with website=profile.website | default:"" % }}
{{website}}
{% endwith %}
</div>
<br/>
<div>
Interest:
{% for Interest in profile.interest.all %}
<span>
{{ interest.name }}{% if not forloop.last %}, {% endif %}
</span>
{% endfor %}
</div>
{% endif %}
{% endwith %}
{% endblock %}
A template tag does not use double curly brackets ({{ … }}), but single ones, with the % immediately followed by that (so {% … %}). The {% with … %} block in your template uses double curly brackets:
{% with website=profile.website|default:'' %}
…
{% endwith %}

Get the first element in the for loops in the Django template

Template:
{% for code in group_codes %}
*_{{ code.build }}_*<br />
{% if test_info.test_type = 0 %}
{{ code.pre_testing_fail }}/{{ code.pre_testing_total }} failed pre-test<br />
{% else %}
{% for shelf in final_shelf_info %}
{{ shelf.build }} <br/>
{% if shelf.build = code.build %}
{{ mr_script_count_func }}/{{ code.script_total }}
<span>MR</span> failed during script<br />
{{gw_script_count_func}}/{{ code.script_total }}
<span>GW</span> failed during script<br />
{{ mr_post_count_func }}/{{ code.post_testing_total }}
MR failed during post-test<br/>
{{ gw_post_count_func }}/{{ code.post_testing_total }}
GW failed during post-test<br/>
{% endif %}
{% endfor %}
<br/>
<br/>
{% endif %}
{% endfor %}
View
def final_shelf_info(self):
shelves = self.bugs_stbs()
shelfList = list()
for shelf in shelves:
shelfList.append(shelf.results_stb_id)
final_info = ResultsStbs.objects.select_related(
'build',
'pre_testing_result',
'script_result',
'post_result',
).filter(
results_stb_id__in=shelfList,
tr_test_case_id=self.kwargs['trTestCaseID'],
).order_by(
'pair_no','shelf_no',
)
for info in final_info:
if info.stb_hw_info_ids:
info.stb_type = info.stb_hw_info_ids.stb_hw_info.stb_type
else:
info.stb_type = None
return final_info
I would like to get the first element in the for loop
{% for shelf in final_shelf_info %}
and compare with another data.
How can I get the first element in the first loop.
First element : Q004.01.55.01.55.19_9423
{{ shelf[0].build }} I tried like that, it did not work.
The output of the for loop:
1234.xx.xx.xx.xx.xx
Any helps would be appreciated.
{% for shelf in final_shelf_info %}
{% if forloop.first %}
Do something with {{ shelf }} since its the first item iterated
{% endif %}
{% endfor %}
More on the {% for %} template loop in the docs.
You could do something like this:
{% for t in things %}
{% if forloop.first %}
// do something
{% endif %}
// do stuff
{% if forloop.last or things.count == 1 %}
// do something
{% endif %}
{% endfor %}
More documentation is available at Django documentation
{% if final_shelf_info.0 == shelf %}
or
{% if final_shelf_info.first == shelf %}

How can i check if values of models are the same in django loop?

I've a loop:
{% for addimg in post.addimg_set.all %}
<p>
{{ addimg.execution }}<br>
{{ addimg.width }} cm x {{ addimg.height }} cm<br>
{{ addimg.year }}
</p>
{% endfor %}
I want to display some data as long as they are different. If they are equal i want it only to display once like:
{% if addimg.execution == addimg.execution %}
{{ addimg.execution }}<br>
{% endif %}
forgive me my python/django still young.
Any suggestions?
You may find your answer in documentation.
Check this out:
https://docs.djangoproject.com/en/1.8/ref/templates/builtins/#ifchanged
I think you are looking for the {% ifchanged %} template tag.
{% ifchanged addimg.execution %}
{{ addimg.execution }}<br>
{% endifchanged %}

Django loop – remove last comma

I have the following loop set up, but need to remove the comma on the last item (it's to replicate a JSON array for cycle2)
{% for product_in_series in series.get_products %}{%spaceless%}
{% with product_in_series.product as product %}
{%if not forloop.first%}
"<img src='{% version product.get_overview 'page_image' %}'>",
{%endif%}
{% endwith %}
{%endspaceless%}{% endfor %}
Cheers,
R
What about this?
{% for product_in_series in series.get_products %}{%spaceless%}
{% with product_in_series.product as product %}
{%if not forloop.first%}
"<img src='{% version product.get_overview 'page_image' %}'>"
{%if not forloop.last%},{%endif%}
{%endif%}
{% endwith %}
{%endspaceless%}{% endfor %}
{{ forloop.last|yesno:",,"|safe }}
, - is a comma
None of the above works for me.
The correct syntax, as in Django 3.0, is as such
{% with querythisandthat as A %}
{% for u in A %} {{ u.interesting_stuff }}
{% if u == A.last %} . {% else %} ; {% endif %}
{% endfor %}
{% endwith %}
The reason is that A.last is not True/False, but it is the last element of the queryset
https://docs.djangoproject.com/en/3.0/ref/models/querysets/#django.db.models.query.QuerySet.first

Django template: check for empty query set

Is there a way to check for an empty query set in the Django template? In the example below, I only want the NOTES header to be displayed if there are notes.
If I put an {% empty %} inside the "for" then it does display whatever is inside the empty tag, so it knows it's empty.
I'm hoping for something that does not involve running the query twice.
{% if notes - want something here that works %}
NOTES:
{% for note in notes %}
{{note.text}}
{% endfor %}
{% endif %}
Clarification: the above example "if notes" does not work - it still displays the header even with an empty query set.
Here's a simplified version of the view
sql = "select * from app_notes, app_trips where"
notes = trip_notes.objects.raw(sql,(user_id,))
return render_to_response(template, {"notes":notes},context_instance=RequestContext(request))
Edit: the view select selects from multiple tables.
Have a look at the {% empty %} tag.
Example from the documentation
<ul>
{% for athlete in athlete_list %}
<li>{{ athlete.name }}</li>
{% empty %}
<li>Sorry, no athletes in this list.</li>
{% endfor %}
</ul>
Link: https://docs.djangoproject.com/en/1.8/ref/templates/builtins/#for-empty
If you are interested in a table, or some kind of heading if there are results, add the forloop.first:
{% for athlete in athlete_list %}
{% if forloop.first %}
Athlete Name:
{% endif %}
{{ athlete.name }}
{% empty %}
Sorry, no athletes in this list.
{% endfor %}
Try {% if notes.all %}. It works for me.
In your view check whether notes is empty or not. If it is then you pass None instead:
{"notes": None}
In your template you use {% if notes %} as normal.
It's unfortunate that you're stuck using a raw query set - they're missing a lot of useful behavior.
You could convert the raw query set into a list in the view:
notes_as_list = list(notes)
return render_to_response(template, {"notes":notes_as_list},context_instance=RequestContext(request))
Then check it as a boolean in the template:
{% if notes %}
Header
{% for note in notes %}
{{ note.text }}
{% endfor %}
{% endif %}
You could also make it happen without conversions using forloop.first:
{% for note in notes %}
{% if forloop.first %}
Header
{% endif %}
{{ note.text }}
{% endfor %}
What about:
{% if notes != None %}
{% if notes %}
NOTES:
{% for note in notes %}
{{ note.text }}
{% endfor %}
{% endif %}
{% else %}
NO NOTES AT ALL
{% endif %}
Your original solution
{% if notes %}
Header
{% for note in notes %}
{{ note.text }}
{% endfor %}
{% endif %}
Works now with Django 1.7 and thanks to QuerySet caching, it does not cost and extra query.
Often the right way to do this is to use the {% with ... %} tag. This caches the query so it runs only once and also gives you more flexibility with your markup than using {% empty %}.
{% with notes as my_notes %}
{% if my_notes %}
<ul>
{% for note in my_notes %}
<li>{{ note }}</li>
{% endfor %}
</ul>
{% else %}
<p>Sorry, no notes available</p>
{% endif %}
{% endwith %}
With this particular example I'm not sure how useful it is but if you're querying Many-to-Many field, for instance, it's likely what you want to do.
Use {% empty %} in django templates
{% if list_data %}
{% for data in list_data %}
{{ data.field_1 }}
{% endfor %}
{% else %}
<p>No data found!</p>
{% endif %}
We can write above code with {% empty %}.
{% for data in list_data %}
{{ data.field_1 }}
{% empty %}
<p>No data found!</p>
{% endfor %}