Search code examples
wagtailwagtail-snippet

How can snippet forms be customized?


This part of the wagtail documentation shows how to customize the form of Page models by subclassing WagtailAdminPageForm and pass the subclass as base_form_class to the Page model.

It also says:

Custom forms for snippets must subclass WagtailAdminModelForm, and custom forms for pages must subclass WagtailAdminPageForm.

However when I try the same using a snippet I get the following error:

ModelForm has no model class specified.

My code:

class ScheduleAdminForm(WagtailAdminModelForm):
    def __init__(self, *args, **kwargs):
        print("Constructor of ScheduleAdminForm")
        super().__init__(*args, **kwargs)


class Schedule(ClusterableModel):
    name = models.CharField(max_length=32)
    base_form_class = ScheduleAdminForm

I also tried to add the model in the Meta class of the ScheduleAdminForm. However then I have a circular use and I can't use the model name in quotes for Meta.model as can be done for model fields.


Solution

  • You can set the model's base_form_class attribute outside the main class definition:

    class Schedule(ClusterableModel):
        name = models.CharField(max_length=32)
    
    
    class ScheduleAdminForm(WagtailAdminModelForm):
        def __init__(self, *args, **kwargs):
            print("Constructor of ScheduleAdminForm")
            super().__init__(*args, **kwargs)
    
        class Meta:
            model = Schedule
            fields = ["name"]
    
    
    Schedule.base_form_class = ScheduleAdminForm