Django在网格行中显示有限的图像

时间:2018-05-23 23:16:35

标签: python django grid

如标题中所述。 是否可以在特定的网格容器中显示特定数量的照片?例如,最多3列,并且行中的卡使用循环? 我能够实现显示定义模型中所有照片的效果, 但我不知道如何设置限制

下面我将介绍负责显示已创建模型的代码片段

forms.py

class ProductsForm(forms.ModelForm):
class Meta:
    model = Product
    fields = ('name', 'description', 'image', 'file_type')

models.py

class Product(models.Model):
name = models.CharField(max_length=20, default='')
description = models.CharField(max_length=100, default='')
file_type = models.CharField(max_length=256, choices=[('image', 'image'), ('thumbnail', 'thumbnail')], default='')

image = models.ImageField(upload_to='products', default='')

def __str__(self):
    return self.name

views.py

def gallery(request):
image = Product.objects.filter(file_type='image')
thumbnail = Product.objects.filter(file_type='thumbnail')
return render(request, 'products/fruits.html', {'img': image, 'thumb': thumbnail})

fruits.html

<!DOCTYPE html>
{% load staticfiles %}
{% load thumbnail %}
{% block body_block %}

<div class="grid-container">
    <div class="card-deck">


        {% for i in thumb %}
            {% thumbnail i.image "150x150" crop="center" as im %}

                <!-- Card -->
                <div class="card mb-4">

                    <!--Card image-->
                    <div class="view overlay">

                        <img src="{{ im.url }}"
                             alt="Card image cap">
                        <a href="#!">
                            <div class="mask rgba-white-slight"></div>
                        </a>
                    </div>

                    <!--Card content-->
                    <div class="card-body">

                        <!--Title-->
                        <h4 class="card-title">Card title</h4>
                        <!--Text-->
                        <p class="card-text">Some quick example text to build on the card title and make up
                            the
                            bulk
                            of
                            the
                            card's
                            content.</p>
                        <!-- Provides extra visual weight and identifies the primary action in a set of buttons -->
                        <button type="button" class="btn btn-light-blue btn-md">Read more</button>

                    </div>

                </div>

            {% endthumbnail %}
        {% endfor %}
    </div>

</div>
{% endblock %}

1 个答案:

答案 0 :(得分:1)

内置Django过滤器divisibleby可以在你的循环中工作,你检查迭代是否可以被(在你的情况下)3整除,然后你打破行跳转到另一个:

{% for i in thumb %}
    {% if forloop.counter|divisibleby:3 %}
         ----------
    {% endif %}
{% endfor %}