Django-filter复选框提交



我正在使用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 %}

它工作正常。但是我想在我的filters.py中添加widget = forms.CheckboxInput(attrs={'onclick': 'this.form.submit();'})以进行复选框输入。我不明白如何添加另一个小部件。请帮我解决这个问题。

创建一个小部件,编写JavaScript脚本,并在widget上使用媒体元类来使用它。在此之后,只需在复选框字段中使用您的小部件。

最新更新