Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/django/23.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python django-模板中的列表列表_Python_Django_Django Templates - Fatal编程技术网

Python django-模板中的列表列表

Python django-模板中的列表列表,python,django,django-templates,Python,Django,Django Templates,我正在尝试呈现一个列表,该列表使用zip()压缩 我想将这个列表的列表渲染到模板,只想显示每个位置的第一个图像 我的位置和图像模型如下: class Location(models.Model): locationname = models.CharField class Image(models.Model): of_location = ForeignKey(Location,related_name="locs_image") img = models.ImageField(

我正在尝试呈现一个列表,该列表使用
zip()
压缩

我想将这个
列表的列表
渲染到模板,只想显示每个位置的第一个图像

我的位置和图像模型如下:

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='')
这是压缩列表。如何仅访问模板中每个位置的第一个图像


列表的列表传递给RequestContext。然后,您可以在模板中引用
图像
列表的第一个索引:

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

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

{% endfor %}
# tags.py
from django import template
register = template.Library()
@register.filter
def get_type(value):
    return type(value).__name__
{%用于位置、评级、图片列表中的列表%}
...
{{images.0}
...
{%endfor%}

我想你应该看看

您还可以根据列表元素的类型(使用Django 1.11)处理模板中的列表元素。

因此,如果您有您描述的视图:

#view.py
# ...
列表的列表=zip(位置、等级、图像)
上下文['list\u of_list']=list\u of_list
# ...
您只需创建一个标记来确定模板中元素的类型:

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

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

{% endfor %}
# tags.py
from django import template
register = template.Library()
@register.filter
def get_type(value):
    return type(value).__name__
然后,您可以检测列表元素的内容类型,并且如果列表元素本身是列表,则仅显示第一个元素。:

{% 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>
{%load tags%}
{#…其他事情}
地点名称
评级
图像
{u列表%中的列表中的列表%}
{列表%中的元素的百分比}
{#如果是列表,只取第一个元素#}
{%如果一个| get_type=='列表'%}
{{an_el.0}}
{%else%}
{{an_el}}
{%endif%}
{%endfor%}
%endfor%}

你能展示你的渲染功能和你的目标模板吗?只是好奇,你为什么要压缩呢?为什么不使用关系?@Bibhas,你的意思是:
all_locations=Location.objects.all()
和在模板中
{%for loc in all_locations%}{%for loc.locs_image.all%}{{img.img.name}{%endfor%}{%endfor%}
是的。为什么不呢?如果您只需要一个项目,可以在模板中使用
slice
标记。