cfx210
cfx210

Reputation: 1

Template and model reuse in Wagtail

I am building a fairly basic Wagtail site and have run into an issue regarding the reuse of models and templates.

Say my site has two kinds of entries:

  1. blog posts and
  2. events.

Both pages look the same and share many model fields (e.g., author, category, intro, etc.). However, there are some model fields that only make sense for the event entry type (e.g., event_date, event_venue).

What would be the ideal way of creating templates and models for this use-case without repeating myself in the code?

Right now, both blog and event entries use the same HTML template and the same model. However, when the user creates a blog post in the Wagtail admin, he or she has to "ignore" the event-specific fields (which may become even more in the future).

Do I have to create two separate template files and two separate models despite both blogs and events being 95% the same code? What would be the correct way to solve this in Wagtail?

Upvotes: 0

Views: 243

Answers (1)

Colin Wong
Colin Wong

Reputation: 56

If you want to maintain it the way it is, contained within one model and template, you could create separate model admins for each pseudo-type (Blogs and Events), and override the queryset function to make each separate modeladmin only show the ones you're looking for, and then edit the panels that are shown on create/edit/delete.

class EventAdmin(ModelAdmin):
    ...


    panels = [
        FieldPanel('your_field'),
        ...
    ]

    def get_queryset(self, request):
        qs = super().get_queryset(request)
        events = qs.filter(your_field__isnull=False)
        return events

More information at https://docs.wagtail.io/en/stable/reference/contrib/modeladmin/index.html

Upvotes: 0

Related Questions