Hi,
Following this tutorial (starting at 7’05), I’m trying to implement a facet filter based navigation within my Django project. Here is my code:
models.py
class ObjetArchi(models.Model):
id = models.AutoField(
primary_key=True,
)
materiau = models.ForeignKey(
'Materiau',
on_delete=models.SET_NULL,
related_name='objets_archi',
blank=True,
null=True
)
class Materiau(models.Model);
id = models.AutoField(
primary_key=True
)
nom = models.CharField(
max_length=125,
blank=True,
null=True
)
views.py
class NoticesListView(ListView):
model = ObjetArchi
template_name = 'notices/index.html'
context_object_name = 'liste_notices'
paginate_by = 20
def get_queryset(self):
qs = super().get_queryset()
materiau = self.request.GET.get('materiau__nom')
if materiau:
qs = qs.filter(type=materiau)
return qs
def get_context_data(self, **kws):
context = super().get_context_data(**kws)
context['materiaux'] = (
self.get_queryset()
.values('materiau__nom')
.annotate(count=Count('id'))
)
return context
urls.py
urlpatterns = [
path('', views.NoticesListView.as_view(), name='notices_list'),
]
notices/index.html
{% for materiau in materiaux %}
<ul>
<a href="?materiau={{ materiau.materiau__nom }}">
{{ materiau.materiau__nom }} ({{ materiau.count }})
</ul>
{% endfor %}
{% if liste_notices %}
<ul>
{% for notice in liste_notices %}
<li><a href="{% url 'notices:detail' notice.id %}">{{ notice.titre }}</a></li>
{% endfor %}
</ul>
{% else %}
<p>Aucune notice n'est accessible.</p>
{% endif %}
The facet shows up with the expected materiau__nom and count, but the queryset doesn’t update when I click on the filter categories. Is there any visible error in the code?
Thanks for your insights!