Wagtail - how to add additional form fields (not from page model) to admin page edit form and get wagtail rendering
This is what I have tried. It works, but the extra field text1 shows up as a simple input field with no label and no cool wagtail rendering. How can I add additional fields to the form and get a cool vaginal visualization 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
source to share
Editing the panel definition for each instance won't work because the panel definition is compiled into an object EditHandler
that is cached at the class level: https://github.com/wagtail/wagtail/blob/48949e69a7a7039cb751f1ee33ecb32187004030/wagtail/wagtailadmin#edL80hand4lers.py
In the case of the code snippet you posted, it looks like moving FieldPanel('text1')
to the RandomPage
content_panels snippet should do the job (although I've never tried it with a non-model field).
source to share
I just realized that fragments can solve my problem. This sounds exactly what I need. So I register my non-page model as a fragment and get the wagtaill rendering. I will check and confirm this.
Snippets documentation: http://docs.wagtail.io/en/v1.9/topics/snippets.html
source to share