I have a model in wagtail with 3 fields
class MyModel(models.Model):
name = models.CharField(_("Name"), max_length=50, unique=True)
tag = models.CharField(_("Tag"), max_length=10, unique=True)
is_valid = models.BooleanField(default=False)
the tag field cannot be changed in CreateView but only in EditView.
So when I click on Add i want this panels
create_panels = [
FieldPanel("name"),
FieldPanel("tag"),
FieldPanel("is_valid"),
]
instead if I click on Edit these are the panels
edit_panels = [
FieldPanel("name"),
FieldPanel("tag", readonly=True),
FieldPanel("is_valid"),
]
With previous versions of Wagtail I was able to perform this using ModelAdmin, but now I am using Wagtail 5.1.1 and if I use ModelAdmin it tells me it is deprecated and to use Snippets.
So I created a SnippetViewSet with a custom EditView and CreateView like this:
class EditableEditView(EditView):
def get_panel(self):
panel = ObjectList(edit_panels)
return panel.bind_to_model(self.object.__class__)
class EditableCreateView(CreateView):
def get_panel(self):
panel = ObjectList(create_panels)
return panel.bind_to_model(self.object.__class__)
class EditableSnippetViewSet(SnippetViewSet):
model = MyModel
edit_view_class = EditableEditView
create_view_class = EditableCreateView
...
The result is that in the EditView the tag field is not readonly and it's duplicated at the end of the page like this. Digging into the code i see that the duplicated field comes from the BoundedPanel.render_form_content, to be precise it comes when it's called self.render_missing_fields(). I can't understand why the tag fields is considered a missing field and why the readonly has no effect.
I found a solution that seems to work for wagtail 5.1.1. First I create two different view:
and the a custom snippet view set
The panel of the edit and create view are based on the create_panels and the edit_panels of the EditableSnippetViewset.
So now i can create my snippet view set like this.