【问题标题】:How to add context querying an external model to another model's template on Wagtail CMS如何在 Wagtail CMS 上将查询外部模型的上下文添加到另一个模型的模板
【发布时间】:2019-12-05 11:26:51
【问题描述】:

我有 wagtail 默认设置的常用 home.HomePage() 模型,这就是它包含的内容:

class HomePage(Page):
advertised_lowest_price = models.FloatField(blank=True, null=True, max_length=20,)
season_year = models.PositiveIntegerField(blank=True, null=True)
season_statement = RichTextField(blank=True, null=True, help_text="THIS MUST BE IN 'h2' TAG! To avoid frontend"
                                                                  " display irregularities, you must use the"
                                                                  " H2 tag",
                                 features=['bold', 'italic', 'hr', 'link', 'document-link', 'embed', 'underline',
                                           'strike-through', 'h2', 'h3'],
                                 )
premium_topic = models.CharField(null=True, blank=True, help_text='Premium Products text', max_length=80)
premium_sub_topic = models.CharField(null=True, blank=True, help_text='Premium Products Sub-topic text',
                                     max_length=80)
article_section_topic = models.CharField(null=True, blank=True, max_length=80)

def get_context(self, request):
    context = super().get_context(request)
    context['home_page'] = HomePage.objects.live().all()

    def carousel_products():
        carousel_items_list = []
        for carousel_item in AdministratorProducts.objects.all():
            carousel_items_list.append(carousel_item.is_carousel())
            return carousel_items_list

    context['carousel_1'] = carousel_products()[0]

    return context

content_panels = Page.content_panels + [
    FieldPanel('advertised_lowest_price'),
    FieldPanel('season_year'),
    FieldPanel('season_statement'),
    FieldPanel('premium_topic'),
    FieldPanel('premium_sub_topic'),
    FieldPanel('article_section_topic'),
]

template = 'home/index.html'

def __str__(self):
    return self.season_statement

也就是说,我还有一个轮播模式,它可以作为其他产品的外壳,这些产品将在索引页面的轮播中显示 > index.html

这是轮播的模型:

class ImageCarousel(Page):
carousel_name = models.CharField(max_length=100, default='ART!')
date_time_stamp = models.DateTimeField(blank=True, null=True, help_text='Date product was added to Carousel.')

class Meta:
    verbose_name_plural = 'Images on the Carousel'

def __str__(self):
    return self.title

content_panels = Page.content_panels + [
    FieldPanel('carousel_name'),
]

template = 'home/index.html'

您可能已经注意到,ImageCarousel 也写入与HomePage 相同的模板,即index.html

同时,我有来自另一个应用程序的另一个模型,它具有ImageCarousel 作为ForeignKey。这是位于'ixorabloom_administrator_products/models.py'的模型:

class AdministratorProducts(Page):
administrator_product_name = models.CharField(max_length=100)
administrator_product_bio = models.TextField(blank=True, null=True)
administrator_product_primary_genre = models.CharField(max_length=4, choices=ART_GENRES, null=True, blank=True)
administrator_product_secondary_genre = models.TextField(help_text='Comma (,) separated list of secondary art '
                                                                   'genres',
                                                         null=True,
                                                         blank=True)
administrator_product_carousel = models.ForeignKey("home.ImageCarousel",
                                                   null=True,
                                                   blank=True,
                                                   on_delete=models.SET_NULL)
administrator_product_carousel_year = models.PositiveIntegerField(help_text="Year to be displayed if this product"
                                                                            " is on the carousel",
                                                                  null=True,
                                                                  blank=True)
administrator_product_date_of_creation = models.DateField(null=True, blank=True, help_text='Date product was made')
administrator_product_website_link = models.URLField(blank=True, null=True, help_text='External website where this'
                                                                                      'product can be found or'
                                                                                      'bought.')
administrator_product_email_address = models.EmailField(blank=True, null=True, help_text='External Mailing site'
                                                                                         'where this product can be'
                                                                                         'ordered.')
administrator_product_picture = models.ForeignKey("wagtailimages.Image",
                                                  null=True,
                                                  blank=True,
                                                  on_delete=models.SET_NULL)
administrator_product_price = models.FloatField(null=True, blank=True)

content_panels = Page.content_panels + [
    FieldPanel('administrator_product_name'),
    FieldPanel('administrator_product_bio'),
    FieldPanel('administrator_product_primary_genre'),
    FieldPanel('administrator_product_secondary_genre'),
    FieldPanel('administrator_product_carousel'),
    FieldPanel('administrator_product_carousel_year'),
    FieldPanel('administrator_product_website_link'),
    FieldPanel('administrator_product_email_address'),
    ImageChooserPanel('administrator_product_picture'),
    FieldPanel('administrator_product_price'),
    FieldPanel('administrator_product_date_of_creation'),
]

class Meta:
    verbose_name_plural = 'Administrator Art Products'

def __str__(self):
    return self.administrator_product_name

def is_carousel(self):
    if self.administrator_product_carousel:
        return True
    else:
        return False

回顾HomePage,那里有一个get_context() 方法。此方法实际上执行一个循环来收集与ImageCarousel 具有ForeignKey 关系的产品(来自管理员)。方法如下:

    def get_context(self, request):
    context = super().get_context(request)
    context['home_page'] = HomePage.objects.live().all()

    def carousel_products():
        carousel_items_list = []
        for carousel_item in AdministratorProducts.objects.all():
            carousel_items_list.append(carousel_item.is_carousel())
            return carousel_items_list

    context['carousel_1'] = carousel_products()[0]

    return context

**您也可以在 ** HomePage().get_context() 中找到它。

这就是问题所在。上下文在前端不起作用。我已经用python manage.py shell 测试了carousel_products() 函数的性能,它完成了工作。这里的问题是它没有显示在由模板提供支持的网页上:'home/index.html'

这是'home/index.html' 的部分,它利用了新添加的上下文:

            {% if carousel_1 %}
        <div class="hs-item">
            <div class="hs-left"><img src="{{ carousel_1.administrator_product_picture.url }}" alt=""></div>
            <div class="hs-right">
                <div class="hs-content">
                    <div class="price">from ₦{{ carousel_1.administrator_product_price }}</div>
                    <h2 style="margin-bottom: 0px;">
                        <span>{{ carousel_1.administrator_product_carousel_year }}</span>
                        <br>
                    </h2>
                    <a href="" class="site-btn">Shop NOW!</a>
                </div>  
            </div>
        </div>
        {% endif %}

我做错了什么?请问我也可以解决这个问题吗?我没有添加到问题中的任何内容,请告诉我,我将提供所需的数据。 我在 Wagtail CMS 上也遇到了非常困难的情况。我真的希望有人能清楚地解释他们的模板设计和使用系统。我的实现都来自 Wagtail 文档。谢谢!

【问题讨论】:

    标签: html django wagtail


    【解决方案1】:

    代码的问题在于HomePage() 模型。准确地说,get_context().carousel_products()。这是对carousel_products()的更正。

            def carousel_products():
                carousel_items_list = []
                for carousel_item in AdministratorProducts.objects.all():
                    if carousel_item.is_carousel():
                        carousel_items_list.append(carousel_item)
                    return carousel_items_list
    

    原始代码的问题在于,for 循环从AdministratorProducts(即AdministratorProducts.objects.all())查询每个产品并检查每个产品是否是轮播项目。返回的是TrueFalse

    在原始代码中,附加到carousel_items_list 的是该检查的返回值(即TrueFalse),而不是产品或产品名称。

    我的解决方案修正了判断函数性能时的错误。现在函数返回正确的数据,模板加载所需的数据。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-09-12
      • 1970-01-01
      • 1970-01-01
      • 2021-04-25
      • 2021-06-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多