python - 如何在Django中过滤模板中的BooleanField?

标签 python django

我正在使用 Django 为我的网站准备一个图片库。我的图像模型中基本上有一个图库模型外键。我的 Image 模型中有一个 BooleanField 来制作封面照片。

我需要的是获取图像之间的真实值。

{% for gallery in gallery_list %}
 <div class="grid-item {{ choices | random }}">
  <a href="#" data-background="{{gallery.images}}#howtofilter?#" data-rel="lightcase:gal" title="Image Caption"></a>
   </div>
{% endfor %}

我检查了试图解决的自定义过滤器的文档,但我无法弄清楚。你能帮我吗?

谢谢

Ps编辑:添加我的模型

    class Gallery(models.Model):
        title = models.CharField(max_length=200,verbose_name=_("gallery_title"),help_text _("Enter the Gallery title"))

    class Image(models.Model):
        title = models.CharField(max_length=200,verbose_name=_("image_title"),help_text _("Enter the Image title"))
        gallery = models.ManyToManyField(Gallery)
        is_cover_photo = models.BooleanField()

最佳答案

您可以在 Gallery 模型中编写一个方法来返回封面图像:

class Gallery(models.Model):
    # other fields
    def cover_image(self):
        return self.image_set.filter(is_cover_photo=True).first()

然后在模板中:

{% for gallery in gallery_list %}
    {% with cover=gallery.cover_image %}
        {% if cover %}
            {# do something with cover image #}
        {% endif %}
    {% endwith %}
{% endfor %}

关于python - 如何在Django中过滤模板中的BooleanField?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46431876/

相关文章:

python - 将多个构建的 BOM(零件列表)保存到 Python 中的文件中

Django 和 Linux,端口转发

python - 如何在 Django 模板中正确列化表格

django - 您将如何在Nginx代理后面的Django应用上管理X509身份验证?

python - 计算 pandas DF 列子集的均值或方差

python - 在 Oozie 中运行 python 脚本时如何导入本地 python 模块?

django - 如何设置 uWSGI vassal 名称以获得更好的日志引用?

python - 如何使用 django-admin.py 运行特定测试?

Python:深入获取项目? (设置图书馆?)

python - 需要将响应保存到文件并在终端中打印状态