django – Wagtail – 如何将额外的表单字段(不是从页面模型)添加到管理页面编辑表单并获取wagtail渲染

这是我试过的.它可以工作,但额外的字段text1呈现为一个普通的输入字段,没有标签,也没有很酷的wagtail渲染.如何在表单中添加额外的字段并获得很酷的wagtail渲染?

这是一个link到WagtailAdminPageForm文档:

class Review(models.Model):

    page = models.OneToOneField(
        'wagtailcore.Page',
        verbose_name=('page'),
        related_name='review',
        on_delete=models.CASCADE)
    text1 = models.CharField(null=True, blank=True, max_length=50)


class RandomPageForm(WagtailAdminPageForm):
    """ Custom form for RandomPage """

    text1 = forms.CharField() # <-- extra field here!

    def __init__(self, data=None, files=None, parent_page=None, *args, **kwargs):
        super(RandomPageForm, self).__init__(data, files, *args, **kwargs)

        if self.instance.id:
            review, created = Review.objects.get_or_create(page_id=self.instance.id)
            print "set form.text1 to model.text1"
            self.fields['text1'].initial = review.text1

        # !!! Below has no effect
        self.instance.content_panels = Page.content_panels + [
            FieldPanel('body'),
            FieldPanel('text1'),
        ]

    def save(self, commit=True):
        page = super(RandomPageForm, self).save(commit=False)
        review, created = Review.objects.get_or_create(page=page)
        review.text1 = self.data["text1"]
        review.save()
        return page

class RandomPage(Page):

    body = RichTextField(blank=True)

    content_panels = Page.content_panels + [
        FieldPanel('body', classname="full"),
    ]

    base_form_class = RandomPageForm

最佳答案 基于每个实例编辑面板定义将不起作用,因为面板定义被编译为在类级别缓存的EditHandler对象:
https://github.com/wagtail/wagtail/blob/48949e69a7a7039cb751f1ee33ecb32187004030/wagtail/wagtailadmin/edit_handlers.py#L804

对于您发布的代码段,看起来将FieldPanel(‘text1’)移动到RandomPage的content_panels片段中应该完成这项工作(尽管我从未尝试过使用非模型字段).

点赞