带有Wagtail和Django的随机图像选择器

问题描述 投票:0回答:1

我试图在Wagtail中获取主页,以显示随机图像。我遵循了Wagtail start guide,并尝试将this hack合并到模板中,但出现错误。

home / models.py:

from django.db import models

from modelcluster.fields import ParentalKey

from wagtail.core.models import Page, Orderable
from wagtail.core.fields import RichTextField
from wagtail.admin.edit_handlers import FieldPanel,InlinePanel
from wagtail.images.edit_handlers import ImageChooserPanel

class HomePage(Page):
    body = RichTextField(blank=True)

    content_panels = Page.content_panels + [
        FieldPanel('body', classname="full"),
        InlinePanel('home_images', label='HomePage Images'),
    ]

class HomeImages(Orderable):
    page = ParentalKey(HomePage, on_delete=models.CASCADE, related_name='home_images')
    image = models.ForeignKey(
        'wagtailimages.Image', on_delete=models.CASCADE, related_name='+'
    )
    caption = models.CharField(blank=True, max_length=64)

    panels = [
        ImageChooserPanel('image'),
        FieldPanel('caption'),
    ]

home / templates / home / home_page.html:

{% extends "base.html" %}
{% load static %}
{% load wagtailcore_tags wagtailimages_tags %}

{% block body_class %}template-homepage{% endblock %}

{% block content %}
{{ page.body|richtext }}
{% with page.thiswillfail|random as item %}
<div>
{% image item.image max-1000x1000 %}
<p>{{ item.caption }}</p>
</div>
{% endwith %}
{% endblock content %}

即使在Wagtail管理界面中添加了一些图像之后,我在主页上也遇到相同的错误:object of type 'DeferringRelatedManager' has no len()

我至少将其范围缩小到home_page.html中的“ with”语句。 ag图像对象可像入门指南中一样在for循环中进行迭代,但似乎不适用于随机函数。因此,如何获取随机图像对象以显示在页面上?

python html django wagtail
1个回答
0
投票

您可以在模板的上下文中获取随机图像,而不是在模板中获取随机图像。这样可以避免应用提到的hack的需要,并且应该使代码更易于将来使用。

每个Wagtail Page可以提供一些方法替代,以自定义模板的呈现方式。这种情况下最简单的是get_cotext-参见https://docs.wagtail.io/en/stable/topics/pages.html#customising-template-context

代码示例

home/models.py
# models.py
class HomePage(Page):
    # ... fields & etc

    def get_context(self, request):
        context = super().get_context(request)

        # Add extra variables and return the updated context
        context['random_image'] = self.home_images.order_by('?')
        return context
home/templates/home/home_page.html
{% extends "base.html" %}
{% load static %}
{% load wagtailcore_tags wagtailimages_tags %}

{% block body_class %}template-homepage{% endblock %}

{% block content %}
{{ page.body|richtext }}

{% image random_image.image max-1000x1000 %}

<p>{{ item.caption }}</p>
</div>
{% endwith %}
{% endblock content %}
© www.soinside.com 2019 - 2024. All rights reserved.