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
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With