Search code examples
wagtailwagtail-snippet

Wagtail: How to order snippets


I am creating Wagtail Snippets for things like Country and State, but also for other features like Transportation Options. I am surprised that there is no ability to Order snippet display in "picker" panels.

"Snippets lack many of the features of pages, such as being orderable in the Wagtail admin" https://docs.wagtail.io/en/stable/topics/snippets.html?highlight=order

This means that if I insert (say) a new Country, it's impossible to make it appear in an alphabetic list, making it very hard for users to find in a panel.

Is there a way, at least, to render snippet items alpha-sorted in the panel?

I would really prefer to be able to order in the Admin UI, so I could have options like "On Subway", "Short Walk to Subway", "Long Drive to Subway" grouped together, rather than alpha-sorted. If I cannot do this with Snippets, is there a way to do something similar with an Orderable, and allow it to be maintained in the Admin UI like Snippets are?

Thanks.


Solution

  • Django allows you to set an ordering property on the model's Meta class to define the default ordering used by queries on that model - listings within the Wagtail admin will use this.

    @register_snippet
    class Country(models.Model):
        name = models.CharField(max_length=255)
    
        class Meta:
            ordering = ['name']
    

    For user-defined orderings, you can define a numeric field (named position, for example) and set the ordering property to that field.