社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  Django

如何在Django的图像列表中找到第一个图像

Saleh • 4 年前 • 663 次点击  

我有一个Django模板渲染结果和图像用于搜索汽车。如下:

{% for item in result %}
<li class="result-row">
    <!-- image box -->

<span>
<a href="#" class="result-image-act" >
    {% for image in item.images_cars_set.all %}


    {% if image.car_images_exists %}
    {% if image.car_images.0 %}
    <img   class="active" src=" {{image.car_images.url}}">
    {% endif %}
    {% if not image.car_images.0 %}
    <img    src=" {{image.car_images.url}}">
    {% endif%}
    {% endif %}
    {% empty %}

    <img  src="{% static 'path/to/default image' %}" class="active">

    {% endfor %}
</a>


<span class="embed-result-price">{{item.price}}</span>
<div class="swipe-wrap">
    <div class="swipe-wrap-lef">
        <span class="move" >
            <div class="swipe-prev">
                <p>&lt;</p>
            </div>
        </span>
    </div>
    <div class="swipe-wrap-rig">
        <span class="move" >
            <div class="swipe-next">
                <p>&gt;</p>
            </div>
        </span>
    </div>
</div>

</span> 

除了我想找到第一个图像并把它放在不同的img标签中,它需要class=“active”,代码工作得很好。这个类在javascript代码中用于向左或向右滑动所有图像。我尝试使用%if image.car_images.0%和%if image.car_images.first%查找第一个图像,但没有成功。我得到的是所有没有活动类的图像。任何帮助或建议。

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/38250
 
663 次点击  
文章 [ 1 ]  |  最新文章 4 年前
Serafeim
Reply   •   1 楼
Serafeim    5 年前

你可以用 {% if forloop.counter0 == 0 %} do something {% endif %} {% if forloop.counter == 1 %} do something {% endif %} 当使用 {% for %} 模板标记。

更多信息: https://docs.djangoproject.com/en/2.1/ref/templates/builtins/#for

因此,您的代码应该是

<a href="#" class="result-image-act" >
  {% for image in item.images_cars_set.all %}
    {% if forloop.counter == 1 %}
      <img class="active" src=" {{image.car_images.url}}">
     {% else %}
       <img src=" {{image.car_images.url}}">
    {% endif %}
  {% empty %}
    <img src="{% static 'path/to/default image' %}" class="active">
  {% endfor %}
</a>