Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wagtail - how do I add extra form fields (not from page model) to admin page edit form and get wagtail rendering

Tags:

django

wagtail

This is what I tried. It works but the extra field text1 is rendered as a plain input field with no label and no cool wagtail rendering. How can I add extra fields to the form and get cool wagtail rendering please?

Here is a link to the WagtailAdminPageForm documentation:

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

like image 552
small mammal Avatar asked Nov 08 '22 23:11

small mammal


1 Answers

Editing the panel definition on a per-instance basis won't work, because the panel definition is compiled into an EditHandler object that gets cached at the class level: https://github.com/wagtail/wagtail/blob/48949e69a7a7039cb751f1ee33ecb32187004030/wagtail/wagtailadmin/edit_handlers.py#L804

In the case of the code snippet you posted, it looks like moving FieldPanel('text1') into RandomPage's content_panels snippet ought to do the job (although I've never tried that with a non-model field).

like image 164
gasman Avatar answered Nov 15 '22 04:11

gasman