I'm using the Django-Filter library !important. For tags, I'm using Django-taggit.
I built the following filter.py:
class TaskFilter(django_filters.FilterSet):
tags = django_filters.ModelMultipleChoiceFilter(widget=forms.CheckboxSelectMultiple, queryset=Task.tags.most_common())
class Meta:
model = Task
fields = ['tags']
However, when I pass this filter
to the template, it doesn't render the tags properly. In particular {{ field.value }} is empty. Let's look at the following cases:
CASE 1.
# template.html
{{ filter.form.tags.errors }}
{% for field in filter.form.tags %}
<label for="{{ field.id_for_label }}"></label>
{{ field.value }}
{% endfor %}
# out
<label for="id_tags_0"></label>
<label for="id_tags_1"></label>
<label for="id_tags_2"></label>
CASE 2.
# template.html
{{ filter.form.tags.errors }}
{% for field in filter.form.tags %}
<label for="{{ field.id_for_label }}"></label>
{{ field }}
{% endfor %}
# out
<label for="id_tags_0"></label>
<label for="id_tags_0"><input type="checkbox" name="tags" value="4" id="id_tags_0">Tag 1</label>
<label for="id_tags_1"></label>
<label for="id_tags_1"><input type="checkbox" name="tags" value="1" id="id_tags_1">Tag 2</label>
<label for="id_tags_2"></label>
<label for="id_tags_2"><input type="checkbox" name="tags" value="2" id="id_tags_2">Tag 3</label>
CASE 3.
# template.html
{{ filter.form.tags.errors }}
{% for field in filter.form.tags %}
{{ field }}
{{ field.label_tag }}
{% endfor %}
#out
<label for="id_tags_0"><input type="checkbox" name="tags" value="4" id="id_tags_0">Tag 1</label>
<label for="id_tags_1"><input type="checkbox" name="tags" value="1" id="id_tags_1">Tag 2</label>
<label for="id_tags_2"><input type="checkbox" name="tags" value="2" id="id_tags_2">Tag 3</label>
I'm trying to understand why this happens. Why can't I get the values as stated in the docs
STEPS TO REPRODUCE
pip install django-filter + add 'django_filters' to APPS
pip install django-taggit + add 'taggit' to APPS
# models.py
class Task(models.Model):
title = models.CharField(max_length=100, blank=False)
tags = TaggableManager()
# Use the API to create an object.
t = Task.objects.create(title="Title")
t.tags.add("Tag 1","Tag 2")
# views.py
def view(request):
f = TaskFilter(request.GET, queryset=Task.objects.all())
return render(request, 'template.html', {'filter': f}