Reputation: 393
I wouldl like to implement categories page using wagtail but it is quite difficult to understand for a novice programmer. When just following the tutorial of wagtail(getting started), the categories field is implemented in their official tutorial but I don't know how to get an access
For instance, in Django, If I define two models like Categories, and Posts, I can access articles that fall under a specific category using Foreign key and making a view using something like Category.posts_set.all()
But how can I do it in wagtail? Thanks for your help in advance
Upvotes: 0
Views: 1302
Reputation: 4138
If you want to list all categories from e.g. a Category Index Page, then you'll need to get all categories and add them to the context. Assuming your model structure is the same as in the tutorial at https://docs.wagtail.io/en/latest/getting_started/tutorial.html#categories, then you can do
class CategoryIndexPage(Page):
# ... other fields go here
def get_context(self, request, *args, **kwargs):
context = super().get_context(request, *args, **kwargs)
context["categories"] = BlogCategory.objects.all()
return context
Then in your template:
{% if categories %}
<h3>Categories</h3>
<ul>
{% for category in categories %}
<li style="display: inline">
{% image category.icon fill-32x32 style="vertical-align: middle" %}
{{ category.name }}
</li>
{% endfor %}
</ul>
{% endif %}
Upvotes: 2