我正在尝试创建一个我想在StructBlock
中使用的自定义StreamField
。在StructBlock
我有4个字段,即:
这是我的代码:
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
。这可能是问题吗?
知道如何解决这个问题吗?
In [27]: wagtail.__version__
Out[27]: '1.13.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)