Django - 重置所有过滤器

问题描述 投票:0回答:2

我试图立即清除单击按钮时的所有过滤器。这是我在filters.py文件和过滤器类上的内容:

class Filters(django_filters.FilterSet):
    id = django_filters.NumberFilter(label=_("ID"))
    name = django_filters.TextFilter(label=_("Name"))

在基本模板中:

        <form id="filters-filters-form" action="javascript:;" onsubmit="onSubmit(this)" class="form form-inline main-filter">
            {% bootstrap_form filter.form layout='inline' %}
            <div>
                <button class="btn ml-auto mr-2" onclick="resetFilters()">Clear all</button>
                {% trans "Apply" as button_text %}
                {% bootstrap_button button_text button_class="btn-primary" %}
            </div>
        </form>

resetFilters()
功能:

var resetFilters = function() {
    let formId = document.getElementById('filters-form')
    let formChildren = formId.childNodes;
    Array.from(formChildren).forEach(formChild => {
        formChild.val(null).trigger('change')
    });
}

有什么简单的方法可以重置所有过滤器吗?

P.S:我需要重置这些过滤器,而不需要任何

id
form-control
,因为它将是可重用的基本模板

django filter django-rest-framework django-templates django-filters
2个回答
0
投票

您只需添加一个按钮并添加表单的 URL :

<a class="btn ml-auto mr-2" href={<pass your URL here>} > Clear All </a>

0
投票

我找到了一种可能很容易理解的方法。在这种情况下,我有带有分页和过滤器表单的列表。 首先,我在模板中添加了一个显示所有内容的按钮

{% if has_filter %}
  <div class="col-1"><button value="clear_filter" name="clarence">
  <a href="{%  url 'msg:comms' %}"></a>
  {% trans 'Clear' %}
  </button></div>
{% endif %}

如果没有按钮名称,则不会包含在请求中

在我看来,我有:

def comms(request):
   template = "mcomms.html"
   ls = Track.objects.all()
   get_dict = request.GET.copy()
   if 'page' in get_dict.keys():
      del get_dict["page"]  # remove the pagination dict

   if 'clarence' in get_dict.keys():  # proces relies on a button named 
    clarence in the template
    get_dict = []  # clear the dict

filtered_set = CommsFilter(get_dict, queryset=ls)
has_filter = any(field in get_dict for field in set(filtered_set.filters))

filtered_qs = filtered_set.qs
page = request.GET.get("page", 1)
paginator = Paginator(filtered_qs, 30)
try:
    obj_page = paginator.page(page)
except PageNotAnInteger:
    obj_page = paginator.page(1)
except EmptyPage:
    obj_page = paginator.page(paginator.num_pages)

context = {
    "title": "Current Communications",
    "objects": obj_page,
    'filter': filtered_set,
    'has_filter': has_filter
}
return render(request, template, context)
© www.soinside.com 2019 - 2024. All rights reserved.