我正在使用django-filter==2.1.0
来实现搜索过滤器。我已经实现了。但是现在我需要通过单击复选框而不是通过搜索按钮进行搜索。我的代码如下:
models.py
class Book(models.Model):
name = models.CharField(max_length=100)
publication = models.ForeignKey(Publication, on_delete=models.CASCADE)
filters.py
class BookFilter(django_filters.FilterSet):
publication = django_filters.ModelMultipleChoiceFilter(queryset=Publication.objects.all(),
widget= forms.CheckboxSelectMultiple)
class Meta:
model = Book
fields = ['publication']
views.py
def test_view(request):
book_list = Book.objects.all()
book_filter = BookFilter(request.GET, queryset=book_list)
temp = book_filter.form
return render(request, 'test.html', {'filter': book_filter})
模板
{% extends 'base.html' %}
{% load widget_tweaks %}
{% block content %}
<form method="get">
{% for choice in filter.form.publication %}
<label>
{{ choice.tag }}
<span class="max-content-width">{{ choice.choice_label }}</span>
</label>
{% endfor %}
<button type="submit">Search</button>
</form>
<ul>
{% for book in filter.qs %}
<li>{{ book.name }}</li>
{% endfor %}
</ul>
{% endblock %}
工作正常。但是我想在widget = forms.CheckboxInput(attrs={'onclick': 'this.form.submit();'})
中添加filters.py
进行复选框输入。我不明白如何添加其他小部件。请帮我解决这个问题。