Search code examples
djangowagtailwagtail-snippet

Adding new Wagtail CMS Snippets


I would like to add new Wagtail Snippet models but cannot find any documentation regarding proper file naming to begin building them; do I place them in my apps model.py file or does it have a specific method similar to wagtailadmin? Thank you.


Solution

  • Snippets are common django models, which are registered using a decorator function. Therefore they live in models.py.

    from django.db import models
    from wagtail.wagtailsnippets.models import register_snippet
    
    @register_snippet
    class Foobar(models.Model):
        foo = models.CharField(max_length=3)
    

    If your app grows you might consider using a package instead of a module. Create a folder called models and copy the contents of models.py into a file called __init__.py. Afterwards create separate modules. E.g. snippets.py inside of this new folder and import them inside of __init__.py

    Sample code:

    models/__init__.py:

    from .snippets import *
    

    models/snippets.py:

    from django.db import models
    from wagtail.wagtailsnippets.models import register_snippet
    
    @register_snippet
    class Foobar(models.Model):
        foo = models.CharField(max_length=3)