List of tuples in django template

I have a list of labels and a list of values ​​in my views, where the nth element in the first list corresponds to the nth element of the second list, I want to display them in order in my template in a list or tab, for example:

- label1 : text1 - label2 : text2 .. 

To do this, I pinned two lists:

 labels = [] texts = [] #function that fills the lists. values = zip(labels,results) context = {'values': values } return render(request,'mypage.html',context) 

Then in my template I tried this:

 {% for value in values %} <ul> <li> {{value}}.</li> </ul> 

But this makes the page with:

  • ('label1', 'text1')
  • ('label2', 'text2')

I also tried to use a dictionary with labels as keys and texts as values, it displays fine, but then the order is not respected, since it is a dict. I thought of other ways of doing this, for example, of two dictionaries for the first line and the other for the second line, but mine, since my knowledge in the python and django templates is not well coordinated, I do not know how to do this.

If anyone can help, I would really appreciate it.

EDIT: Actually, I found the answer two minutes after I asked about it, but I will leave it in case he can help anyone. In the template, I just did:

 {% for labels, texts in values %} <ul> <li> {{labels}} : {{texts}}.</li> </ul> 
+4
source share
1 answer

Use str.join :

 values = [" : ".join(x) for x in zip(labels,results)] 

And pass this list to the template.

With just zip you need to unzip inside the template:

 values = zip(labels,results) {% for label, text in values %} <ul> <li> {{ label }} : {{ text }}</li> </ul> 
+3
source

Source: https://habr.com/ru/post/1494029/


All Articles