fetching list elements using jinja2 under flask app - python

I have a list say list[a][b] of length 10.
I want to print from list[0][b] to list[10][b] and use it in jinja2 template.
{% for i in test %}
<p> {{test[i][0]}} </p>
{% endfor %}
throws error:
UndefinedError: list object has no element

You actually get the element out of the list when you iterate over it, not the index value:
{% for row in test %}
{# Note that we subscript `row` directly,
(rather than attempting to index `test` with `row`) #}
<p>{{ row[0] }}</p>
{% endfor %}

If you want to make sure to always have the first 10:
{% for test in tests[0:10] %}
<p> {{ test[1] }} </p>
{% endfor %}

Related

How do minus in django template [duplicate]

It is able to write {{ myval.add:5 }}, {{ myval|add:value }} and even {{ myval|add:-5 }}.
However, I can't find out what I should type to add value * -1 like {{ myval|add:-value }}. This doesn't work, sadly.
You need to use double quotes:
{{ myval|add:"-5" }}
This subtracts five from myval.
The built-in Django template tags/filters aren't all-encompassing, but it's super easy to write your own custom template tags: https://docs.djangoproject.com/en/dev/howto/custom-template-tags/
You could make your own subtract template tag pretty easily:
#register.filter
def subtract(value, arg):
return value - arg
Use django-mathfilters from PyPI: https://pypi.python.org/pypi/django-mathfilters
To install :
$ pip install django-mathfilters
Then add mathfilters in your INSTALLED_APPS.
In template:
{% load mathfilters %}
<ul>
<li>8 + 3 = {{ 8|add:3 }}</li>
<li>13 - 17 = {{ 13|sub:17 }}</li>
{% with answer=42 %}
<li>42 * 0.5 = {{ answer|mul:0.5 }}</li>
{% endwith %}
{% with numerator=12 denominator=3 %}
<li>12 / 3 = {{ numerator|div:denominator }}</li>
{% endwith %}
<li>|-13| = {{ -13|abs }}</li>
</ul>
I recently started working with Django and stumbled upon this one as well: I needed a very simple template loop that stops printing after n times and shows a "more" link to toggle the rest of the items.
With great interest I read the struggle of people trying to understand why this is not being added to the Django default filters (since before 2013). I didn't feel like creating a custom template tag and I kind of found a way to subtract 2 variables using strings and add in combination with with and stringformat
Let's say I have a list of items where I want to print the first 2 and hide the rest, showing how many hidden items are there, eg.
John, Anna and 5 others like this (when given a list of 7 items)
As long as the number of visible items is harcoded in the template (eg. 2), it's possible to add the negative 2 |add:"-2", but I wanted the number of visible items to be a variable as well. The Math-filter library as suggested above doesn't seem up to date (I haven't tested it with Django 2.x).
The trick seems to be to use the add helper to concat the strings "-" with the integer as string, so it can be coerced back to a negative integer in a any consecutive calls to the add helper. This doesn't work however if the value is not a string, so that's where the stringformat helper comes in.
With string value
template posts.html (note how visible is explicitely passed as string - alternative below)
{% for post in posts %}
<h4>{{ post.title }}</h4>
...
{% include 'show_likes.html' with likes=post.likes visible="3" %}
{% endfor %}
template show_likes.html (note the add:0 to make the boolean operator work)
{% with show=visible|default:"2" %}
{% for like in likes %}
{% if forloop.counter <= show|add:0 %}
{% if not forloop.first %},{% endif %}
{{ like.username }}
{% endif %}
{% endfor %}
{% if likes|length > show|add:0 %}
{% with rest="-"|add:show %}
and {{ likes|length|add:rest }} more
{% endwith %}
{% endif %}
like this
{% endwith %}
Alternative with integer
You could just convert your integer to a string in the calling template using |stringformat:"d"
If however the number of visible items you want to show is an integer, you'll have to add a call to stringformat:"d" to have it converted to string
template posts.html
{% for post in posts %}
<h4>{{ post.title }}</h4>
...
{% include 'show_likes.html' with likes=post.likes visible=3 %}
{% endfor %}
template show_likes.html
{% with show=visible|default:2 %}
{% with show_str=show|stringformat:"d" %}
{% for like in likes %}
{% if forloop.counter <= show %}
{% if not forloop.first %},{% endif %}
{{ like.username }}
{% endif %}
{% endfor %}
{% if likes|length > show|add:0 %}
{% with rest="-"|add:show_str %}
and {{ likes|length|add:rest }} more
{% endwith %}
{% endif %}
{% endwith %}
{% endwith %}
Since I'm a very beginner with Django and Python, I'm pretty sure this approach is far worse than actually creating a custom helper! So I'm not suggesting anyone should be using this. This was just my attempt on trying to solve this with the available template helpers and without any custom stuff.
Hope this helps
Lo primero es multiplicar por -1 para convertirlo en una valor negativo y guardarlo en una variable y posterior a usar la suma
The first thing is to multiply by -1 to turn it into a negative value
and save it in a variable and then use the add
{% widthratio val2 1 -1 as result %}
{{result|add:val1}}
After search I found that I can make {% with var=value %} with filters to make the arithmetic operations "with other variables or not"
For example: I have x = 5 and y = 3 and need to add the y's value to x value, all what I need is these steps:
1- Create variable x : {% with x=5 %}
2- Create variable y : {% with y=3 %}
3- In my HTML tags, say <h1>, write that : <h1>{{ x|add:y }}</h1>
4- Close the y's with : {% endwith %}
5- Close the x's with : {% endwith %}
Hope it works with you, it worked with me.
{% with i=3 %}
{% with x=1 %}
<h1>{{i|add:x}}</h1> <!-- result is 4 -->
{% endwith %}
{% endwith %}

django template print out by filter id value

I want to print value by id in database,And don't know which keywords to find in Google.
in my views.py, I send transen = TransEn.objects.all() to template
and this will print all datas from database:
{% for words in transen %}
{{words.words|safe }}
{% endfor %}
But I want to print by the value of the id Like:
(Because they are words in English for translating website)
I don't know how to write this in template, please guide me, Thank you very much.
<div><span> TransEn.objects.filter(id='2') </span></div>
<div> TransEn.objects.filter(id='3') </div>
UPDATE:
I have found a method:
I can use if tag, but are there another ideas??
<div>
{% for words in transen %}
{% if words.id == 2 %}
{{ words.words|safe }}
{% endif %}
{% endfor %}
</div>
<div>
{% for words in transen %}
{% if words.id == 3 %}
{{ words.words|safe }}
{% endif %}
{% endfor %}
</div>
If you want to access each item in the QuerySet individually, by index, you should cast it to a list first. You should change your views.py to:
transen = list(TransEn.objects.all())
And then in your template you can access them by index like so:
<div><span> {{ transen.1.words }} </span></div>
<div> {{ transen.2.words }} </div>
A warning from the Django docuemtnation about casting a QuerySet to a list:
Be warned, though, that this could have a large memory overhead, because Django will load each element of the list into memory. In contrast, iterating over a QuerySet will take advantage of your database to load data and instantiate objects only as you need them.

How can I Iterate through the same dictionary multiple times in a Django template?

I have a dictionary called categories. And I just want to iterate through this dictionary twice in a Django template. Below is my code:
<div class="first">
{% for category in categories %}
<li class="{{category.name}}">{{category.name}</li>
{% endfor %}
</div>
<div class="lenDict">
<h2>{{categories|length}}</h2>
</div>
<div class="second">
{% for category in categories %}
{% for facet in allFacets %}
{% if category.name == facet.category %}
<p id="{{facet.id}}">{{facet.facet}}</p>
{% endif %}
{% endfor %}
{% endfor %}
</div>
When I do it like this the first loop under the div first works fine.
But when it comes to the second loop under the div second it gives no result.
Also the code under the div lenDict also gives no result.
Are there any limitations in Django templates that we cannot iterate the same dictionary twice?
Any help will be appreciated.
To iterate through an entire dict in Python, you should use .iteritems(). It creates a new iterator over the (key, value) pairs of the dict. You could also use items() if you wanted a list of items instead.
<div class="first">
{% for key, value in categories.iteritems() %}
<li class="{{ key }}">{{ value }}</li>
{% endfor %}
</div>
<div class="lenDict">
<h2>{{ categories|length }}</h2>
</div>
<div class="second">
{% for key, value in categories.iteritems() %}
{% for facet in allFacets %}
{% if key == facet.category %}
<p id="{{facet.id}}">{{facet.facet}}</p>
{% endif %}
{% endfor %}
{% endfor %}
</div>
Note that your dict will be unordered. If you want to preserve the orders of the keys, use an OrderedDict.
So I think this works. I think your issue is facet.category. Is this a fk? because if this is a fk the if statement should be
{% if category.id == facet.category %}
In python iterators don't need to be reset, so I don't think you have to reset your iterators in the tamplate.
Note: I would leave this is in a comment but rep isn't high enough.

Django {% blocktrans %}: How to handle pluralization inside a for loop?

I have the following loop in my Django template:
{% for item in state.list %}
<div> HTML (CUSTOMERS BY STATE) </div>
<!-- print sum of customers at bottom of list -->
{% if forloop.last %}
<h4>{{ forloop.counter }} Valued Customers</h4>
{% endif %}
{% endfor %}
Obviously, if I end up with only one customer, I'd like to print singular "Valued Customer"
According to Django's docs, one should use blocktrans. Tried the following, a few flavors of nesting:
{% blocktrans count %}
{% if forloop.last %}
<h4>
{{ forloop.counter }}
Valued Customer
{% plural %}
Valued Customers
</h4>
{% endif %}
{% endblocktrans %}
Keep getting TemplateSyntaxError: Invalid block tag: 'blocktrans', expected 'empty' or 'endfor'
Is there no way to combine with another loop? Any ideas how to solve? Thanks!
Here is the working code, thanks to alko:
{% load i18n %}
<!-- ... -->
{% if forloop.last %}
<h4>
{{ forloop.counter }}
{% blocktrans count count=forloop.counter %}
Valued Customer
{% plural %}
Valued Customers
{% endblocktrans %}
</h4>
{% endif %}
Probably, you forgot to load translation tags. Add following line at the top of your template:
{% load i18n %}
After you fix that, note that for a blocktrans tag after count a variable, whose value will serve for plural detection, should be specified, so you probably need something like
{% blocktrans count count=forloop.counter %}
To pluralize use this:
Customer{{ forloop.counter|pluralize }}

In a Django template for loop, checking if current item different from previous item

I'm new to django and can't find a way to get this to work in django templates. The idea is to check if previous items first letter is equal with current ones, like so:
{% for item in items %}
{% ifequal item.name[0] previous_item.name[0] %}
{{ item.name[0] }}
{% endifequal %}
{{ item.name }}<br />
{% endforeach %}
Maybe i'm trying to do this in wrong way and somebody can point me in right direction.
Use the {% ifchanged %} tag.
{% for item in items %}
{% ifchanged item.name.0 %}
{{ item.name.0 }}
{% endifchanged %}
{% endfor %}
Also remember you have to always use dot syntax - brackets are not valid template syntax.

Categories

Resources