ParentalKey不在StructBlock中呈现

时间:2018-03-02 21:20:37

标签: python django python-3.x wagtail wagtail-streamfield

我正在尝试创建一个我想在StructBlock中使用的自定义StreamField。在StructBlock我有4个字段,即:

  • background_style
  • 标题
  • 图像
  • 类别

这是我的代码:

from django.db import models

from wagtail.wagtailcore.models import Page
from wagtail.wagtailcore.fields import StreamField

from wagtail.wagtailcore import blocks
from wagtail.wagtailimages.blocks import ImageChooserBlock
from wagtail.wagtailimages.edit_handlers import ImageChooserPanel
from wagtail.wagtailsnippets.models import register_snippet

from wagtail.wagtailadmin.edit_handlers import FieldPanel, StreamFieldPanel
from modelcluster.fields import ParentalKey

from .vars import BackgroundChoices


class BaseBlock(blocks.StructBlock):
    background_style = blocks.ChoiceBlock(choices=BackgroundChoices, icon='color', required=False)


@register_snippet
class LeadCaptureCategory(models.Model):
    name = models.CharField(max_length=255)
    about = models.CharField(max_length=255, blank=True)
    icon = models.ForeignKey(
        'wagtailimages.Image', null=True, blank=True,
        on_delete=models.SET_NULL, related_name='+'
    )

    panels = [
        FieldPanel('name'),
        FieldPanel('about'),
        ImageChooserPanel('icon'),
    ]

    def __str__(self):
        return self.name

    class Meta:
        verbose_name_plural = 'Lead Capture Categories'


class LeadCaptureForm(BaseBlock):
    title = blocks.CharBlock(required=False)
    image = ImageChooserBlock(required=False)
    category = blocks.BlockField(ParentalKey('LeadCaptureCategory'))

    class Meta:
        icon = 'plus-inverse'
        label = 'lead capture form'.title()
        admin_text = label
        template = 'home/blocks/lead_capture_form.html'


class HomePage(Page):
    template = 'home/home_page.html'
    menu = models.CharField(max_length=128, blank=True)
    body = StreamField([
        ('lead_capture_form', LeadCaptureForm()),
    ], blank=True)

    content_panels = Page.content_panels + [
        StreamFieldPanel('body'),
    ]

admin中的其中3个字段已正确呈现,但category除外(根本不呈现)。您可以看到category基于modelcluster.fields.ParentalKey。这可能是问题吗?

enter image description here

知道如何解决这个问题吗?

In [27]: wagtail.__version__
Out[27]: '1.13.1'

1 个答案:

答案 0 :(得分:1)

你是对的,你不能像那样从ParentalKey构建一个块。看起来你真正想要的是SnippetChooserBlock

from wagtail.wagtailsnippets.blocks import SnippetChooserBlock

class LeadCaptureForm(BaseBlock):
    title = blocks.CharBlock(required=False)
    image = ImageChooserBlock(required=False)
    category = SnippetChooserBlock(LeadCaptureCategory)