django - list of lists in template

一世执手 提交于 2021-02-18 17:57:06

问题


I am trying to render a list of lists zipped with zip().

list_of_list = zip(location,rating,images)

I want to render this list_of_list to template and want to show only the first image of each location.

my location and image models are these:

class Location(models.Model):
  locationname = models.CharField

class Image(models.Model):
  of_location = ForeignKey(Location,related_name="locs_image")
  img = models.ImageField(upload_to=".",default='')

here is the zipped list. How can I access only the first image of each location in template?

enter image description here


回答1:


Pass the list_of_lists to the RequestContext. Then you can reference the first index of the images list in your template:

{% for location, rating, images in list_of_lists %}

...
<img>{{ images.0 }}</img>
...

{% endfor %}

How to render a context




回答2:


I think you should have a look at django-multiforloop.




回答3:


You can handle list elements in your template also based on their type (with Django 1.11 ).

So in case you have the view you describe:

# view.py
# ...
list_of_lists = zip(location,rating,images)
context['list_of_lists'] = list_of_lists
# ...

All you need to do is create a tag to determine the type of your elements in the template:

# tags.py
from django import template
register = template.Library()
@register.filter
def get_type(value):
    return type(value).__name__

Then you can detect the content type of a list element and only display the first element if the list element is a list itself:

{% load tags %}
{# ...other things #}
<thead>
  <tr>
    <th>locationname</th>
    <th>rating</th>
    <th>images</th>
  </tr>
</thead>
<tbody>
  <tr>
    {% for a_list in list_of_lists %}
    {% for an_el in a_list %}
    <td>
        {# if it is a list only take the first element #}
        {% if an_el|get_type == 'list' %}
        {{ an_el.0 }}
        {% else %}
        {{ an_el }}
        {% endif %}
    </td>
    {% endfor %}
  </tr>
  % endfor %}
</tbody>



来源:https://stackoverflow.com/questions/15703945/django-list-of-lists-in-template

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!