F.M.F.
F.M.F.

Reputation: 2292

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.

Upvotes: 0

Views: 177

Answers (2)

Rich - enzedonline
Rich - enzedonline

Reputation: 1258

It is definitely possible to declare as you've done, I do this myself:

    from core.forms.restricted_panels_admin_forms import \
        RestrictedPanelsAdminModelForm
    
    @register_snippet
    class StoreDepartment(ClusterableModel):
        base_form_class = RestrictedPanelsAdminModelForm
        ....

RestrictedPanelsAdminModelForm subclasses WagtailAdminModelForm

Only difference I can see is that it's importing the form, can't imagine that's the cause though.

Upvotes: 0

gasman
gasman

Reputation: 25227

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

Upvotes: 2

Related Questions