I want to loop over lists using a list containing the lists name, eg :
{% set album = ['one','two'] %}
{% set one = ['a','b','c'] %}
{% set two = ['d','e','f'] %}
{% for alb in album %}
{% for songs in alb %}
{{ songs }}
{%- endfor %}
{%- endfor %}
but it doesn't work...how can I achieve something like that ? (I want to split the lists because they are long)
Thank's
Create album from previously set lists one and two and it will work
{% set one = ['a','b','c'] %}
{% set two = ['d','e','f'] %}
{% set album = [one, two] %}
{% for alb in album %}
{% for songs in alb %}
{{ songs }}
{%- endfor %}
{%- endfor %}
Related
In my Jinja2 code, Macro getLisCustomer() is used to get a returned list of customer ID and is defined as below:
{% macro getLisCustomer() %}
{% set myList = [] %}
{% if myList.append('CU001') %}{% endif %}
{% if myList.append('CU002') %}{% endif %}
{% if myList.append('CU003') %}{% endif %}
{{myList}}
{% endmacro %}
However, when I tried to get an individual customer ID from macro getLisCustomer(), I get a list of single character instead of individual customer ID in a list.
{% set TotalList = getLisCustomer() %}
{% for row in TotalList %}
<p>{{row}}</p>
{% endfor %}
The result is something like this [ ' C U 0 0.....
What's wrong? How can I get list element from macro getLisCustomer() in Jinja2?
Added: I just realized that the root cause might be that my macro does not return a list but a list-like string, that is why in for-loop return every single character instead of list element. Therefore, how could we convert a list-like string into an actual list?
You can do as simple as a comma-separated list representation which you split into a list when consuming:
{% macro getLisCustomer() -%}
{% set myList = [] -%}
{% if myList.append('CU001') %}{% endif -%}
{% if myList.append('CU002') %}{% endif -%}
{% if myList.append('CU003') %}{% endif -%}
{% for i in myList %}{{ i }}{% if not loop.last %},{% endif %}{% endfor -%}
{% endmacro %}
This could be further simplified, because you don't really need to create myList, you can print the values immediately.
Then:
{% set TotalList = getLisCustomer().split(',') -%}
{% for row in TotalList %}
<p>{{row}}</p>
{%- endfor %}
Or if for some reason you wanted to implement a data exchange protocol you could create custom filters in Python (see my first edit based on how Ansible extends Jinja2).
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 %}
My template doesnt render the key , values for the variable table which is a dictionary.
{% for key, value in table.items %}
<p> {{key}} : {{value}}</p>
{% endfor %}
The was how the variable 'table' was derived. Client is a model and Client_FirstName is the attribute of the model.
table = Client.objects.filter(Client_FirstName__startswith='p').values()
I am just trying to do a database query which i just learn from here
There may not be any data in the database. Try this.
{% if table|length %}
{% for key, value in table.items %}
<p> {{ key }} : {{ value }}</p>
{% endfor %}
{% else %}
<div>There are no data in the database</div>
{% endif %}
I was rendering the database values wrongly on the template , this is how it should be done for a list of dictionary
{% for x in table %}
{% for key,values in x.items %}
<p> {{key}} : {{values}} </p>
{% endfor %}
{% endfor %}
I want to get the list of songs under the list of artists.
My artist class just contains the artists first and last name.
My song class contains a foreign key of an artist along with the song title.
I am able to list the artists but when I try to list the songs of the artist I get and error in my {% endif %} that ends my if statement {% if song %}.
{% extends "base.html" %}
{% block heading %}Music Catalog{% endblock %}
{% block content %}
{% if user.username %}
<p>Welcome {{ user.username }}!</p>
{% if artist %}
<u1>
{% for singer in artist %}
<li>{{ singer.firstname }} {{ singer.lastname }}</li>
{% if song %}
<u1>
{% for songs in song %}
{% if (songs.artist.firstname == singer.firstname
and songs.artist.lastname == singer.lastname) %}
<li>{{ songs.title }}</li>
{% endif %}
{% endfor %}
</u1>
{% endif %}
{% endfor %}
</u1>
{% else %}
<p>No artists were found in the music catalog.</p>
{% endif %}
{% else %}
<p>You need to login to see your music catalog.</p>
{% endif %}
{% endblock %}
enter code here
I don't think so, in the template language if statement you can use round bracket it won't parse. Try by removing it...
{% if songs.artist.firstname == singer.firstname and songs.artist.lastname==singer.lastname%}
It seems that your view should be handling more of this logic. Like Raunak Agarwal mentioned if you are passing your song or songs in to the template then each one is going to be the same.
It's very strange as well to be doing a
{% for songs in song %}
That just doesn't read right.
I would visit the view a little closer. I had written some more below. After looking over your code though taking a look at the view as well as the model would shed some light on things and allow for a much better help/answer to be given.
As you said My song class contains a foreign key of an artist along with the song title. - why don't you just use the regroup feature?
{% regroup song by artist as artist_list %}
<ul>
{% for artist in artist_list %}
<li>{{ artist.grouper }}
<ul>
{% for songs in artist.list %}
<li>{{ songs.title }}</li>
{% endfor %}
</ul>
</li>
{% endfor %}
</ul>
Yes, your if song line is incorrect. It's quite clear from the template that you don't even have a song attribute at that point. Where is it supposed to be coming from? Presumably it's a related set on singer, but you haven't said so in the template.
You probably want something like this:
{% for singer in artist %}
<li>{{ singer.firstname }} {{ singer.lastname }}
{% with songs as singer.song_set.all %}
{% if songs %}
<ul>
{% for song in songs %}
<li>{{ song.title }}</li>
{% endfor %}
</uL>
{% endif %}
{% endwith %}
</li>
{% endfor %}
I've also removed that comparison of artist firstname and lastname, that didn't seem to make sense: you're already iterating through the set of songs from that artist, so no comparison is needed.
I have dictionary with arrays inside:
dicarr = {'category': ['post1','post2', 'e.g.'], 'category2': ['post1','post2']}
Array is filled in one cycle:
dicarr = {}
for category in Categories.objects.all():
category_posts = Post.objects.filter(category=category)
dicarr[category] = [post for post in category_posts ]
How can i get access to array from django template? I tried:
{% for arrdic in dicarr %}
{{ arrdic.name }}
{% for i in arrdic.posts %}
{{ i.name }}
{% endfor %}
{% endfor %}
But isn't working.
Assuming you have a foreign key pointing to Category on your Post, you don't even need to do it this complicated. All you need to is pass this to the template:
categories = Category.objects.all()
Then you can iterate like this in the template:
{% for category in categories %}
{{ category.name }}
{% for post in categories.post_set.all %}
{{ post.name }}
{% endfor %}
{% endfor %}
You can do this with any foreign key relationships. Hope that answers your question!
Following your original code, your template should be (also see for tag docs):
{% for category, posts in dicarr.items %}
{{ category.name }}
{% for post in posts %}
{{ post.name }}
{% endfor %}
{% endfor %}
But this isn't the best way to do this, because your view will produce number of queries equal to the number of categories. See my answer to a similar question for a more efficient solutions.