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

时间:2017-03-31 04:21:59

标签: django wagtail

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

以下是WagtailAdminPageForm文档的link

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

Attached is an image of the plain input box

2 个答案:

答案 0 :(得分:1)

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

对于您发布的代码段,看起来将FieldPanel('text1')移动到RandomPage的content_panels片段应该可以完成这项工作(虽然我从未尝试过使用非模型字段。)

答案 1 :(得分:0)

我刚刚意识到片段可能会解决我的问题。这听起来正是我需要的。所以我将我的非页面模型注册为片段并获得wagtaill渲染。我会检查一下并确认。

有关代码段的文档: http://docs.wagtail.io/en/v1.9/topics/snippets.html