How to declare a variable and increment it in Django templates - django

How to initialize a numerical variable in Django templates.
{% with i=1 %}
{% for cont in data %}
{% if i|divisibleby:3 %}
{{ forloop.i }}
<!-- HTML -->
{% elif i|divisibleby:2 %}
{{ forloop.i }}
<!-- HTML -->
{% else %}
{{ forloop.i }}
<!-- HTML -->
{% endif %}
{% endfor %}
Getting this error due to {% with i=1 %}
TemplateSyntaxError at /tools-dash/
Unclosed tag on line 21: 'with'. Looking for one of: endwith.
The variable i is not being incremented by each {{ forloop.i }}. For each row in DB I get the same template in else part. How this can be changed to alternative ones.

There's no need to create a new variable. You can use your normal for loop, and check if forloop.counter is divisible by 3 or 2. Like so:
{% for cont in data %}
{% if forloop.counter|divisibleby:3 %}
{{ forloop.counter }}
<!-- HTML -->
{% elif forloop.counter|divisibleby:2 %}
{{ forloop.counter }}
<!-- HTML -->
{% else %}
{{ forloop.counter }}
<!-- HTML -->
{% endif %}
{% endfor %}

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 %}

How to display text if the field is empty?

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.

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 %}

Django: Possible to use variable from parent for loop within child if statement

Is it possible to use a variable from the parent's for loop within the child's if statement?
This is the example:
{% for ruleset in rulesets %}
<div>{{ ruleset.0 }}</div>
<ul>
{% for rule in rules %}
{% if rule.0 = {{ ruleset.0 }} %}
<li>{{ rule.1 }}</li>
{% else %}
<!-- Nothing -->
{% endif %}
{% endfor %}
</ul>
{% endfor %}
The error I am getting is:
raise TemplateSyntaxError("Could not parse the remainder: '%s' from '%s'" % (token[upto:], token))
TemplateSyntaxError: Could not parse the remainder: '{{' from '{{'
Which I presume means that it couldn't understand {{ ruleset.0 }} within the if statement. Any suggestions as to how to resolve this?
Your syntax is incorrect: you can't use {{ ... }} inside a {% ... %} statement.
This should work, as the inner for loop should inherit the scope of the outer for loop:
{% for ruleset in rulesets %}
<div>{{ ruleset.0 }}</div>
<ul>
{% for rule in rules %}
# = is an assignment operator (which doesn't work in templates),
# == is the equality operator, which you want to use.
# alternatively you can use {% ifequal rule.0 ruleset.0 %}{% else %}{% endifequal %}
{% if rule.0 == ruleset.0 %}
<li>{{ rule.1 }}</li>
{% else %}
<!-- Nothing -->
{% endif %}
{% endfor %}
</ul>
{% endfor %}

Why doesn't django like my dictionary?

I'm new to django, and desperately trying to figure out why I can't get a set of dictionary objects to render. Here is a snippet of the template--with some pprints for debugging:
<ul>
{% with req.requirement_id as reqid %}
req.requirement_id: {{ req.requirement_id|pprint }}<br />
reqid: {{ reqid|pprint }}<br />
e_quals: {{ e_quals|pprint }}<br />
e_quals.reqid: {{ e_quals.reqid|pprint }}<br />
{% for qual in e_quals.reqid %}
qual.qual_type: {{ qual.qual_type }}
{% if qual.qual_type == "self" %}
<li>Only self-endorsements.</li>
{% endif %}
{% if qual.qual_type == "other" %}
<li>No self-endoresements.</li>
{% endif %}
{% if qual.qual_type == "hasa" %}
<li>Endorser must hold an active {{ qual.qual_data }} badge.</li>
{% endif %}
{% endfor %}
{% endwith %}
</ul>
And here is what I get as an output:
req.requirement_id: u'man_keephead'
reqid: u'man_keephead'
e_quals: {u'man_keephead': [<EndorsementQual: man_keephead_others>, <EndorsementQual: man_keephead_man>], u'man_trustself': [<EndorsementQual: man_trustself_self>], u'man_waiting': [<EndorsementQual: man_waiting_other>]}
e_quals.reqid: ''
I really seems like--given that reqid and that e_quals dictionary, e_quals.reqid should produce that list of objects. I'm not sure what I'm missing.
You can't do this sort of indirect variable resolution in Django's template language. It will always interpret e_quals.req_id as e_quals["req_id"] - ie as a literal key.
You'll need to create a simple template filter:
#register.filter
def dict_get(my_dict, key):
return my_dict.get(key)
{{ e_quals|dict_get:req_id }}