1

In wagtail, is there a good way to add the same fields to every page model? I am thinking about things like SEO data fields and search meta information that virtually every page would like to implement. I cannot seem to find a good way to do this using Wagtail.

David B
  • 345
  • 3
  • 14

1 Answers1

5

You can use abstract classes (you then inherit from this base class instead of Wagtail's Page) or mixins (you then inherit from both the mixin and Wagtail's Page) for that.

# Example with Abstract class
class BasePage(wagtail.wagtailcore.models.Page):
    seo_image = models.ForeignKey(...)

    class Meta:
        abstract = True


class MyPage(BasePage):
    pass


# Example with mixins
class SEOMixin(django.db.models.Model):
    seo_image = models.ForeignKey(...)

    class Meta:
        abstract = True

class MyPage(SEOMixin, wagtail.wagtailcore.models.Page):
    pass

Using abstract classes is probably the simplest, but all your pages will always inherit all the fields defined on the base class. Using mixins on the other hand is more flexible as you can have multiple mixins (SEOMixin, ThumbnailMixin, etc) and combine them depending on your need.

Loïc Teixeira
  • 1,404
  • 9
  • 19
  • Yea. I thought about that approach. Seems a bit intense for an existing project. Not a terrible idea though. – David B Dec 14 '17 at 20:36
  • Ok. Yes using Mixins is by far the best approach I have tests. Thanks Loïc Teixeira. You answer was just a little confusing because Mixins in python are so poorly documented. Loïc Teixeira's SEOMixin class, while it looks like an abstract class, in the Django world, actually functions as a Mixin. This is a good resource for how to use a Mixin with a Django model, https://stackoverflow.com/questions/3254436/django-model-mixins-inherit-from-models-model-or-from-object – David B Dec 14 '17 at 23:43
  • 1
    Indeed, mixins with Django are a little bit different from pure Python mixins. That a great link and I'll make sure to include it in the future when I talk about Django mixins. Thanks. – Loïc Teixeira Dec 17 '17 at 22:03