如何在Django Tables2的第二页中保留搜索过滤器

时间:2019-02-16 16:40:20

标签: python django django-forms django-tables2

我在django table2中应用搜索时遇到了一个问题,实际上我创建了一个搜索过滤器,并在django orm上应用并将其分页地传递到django table2的configure()函数中,但是每当我按下一页时,搜索过滤器的值清空并且搜索不起作用。 有人可以建议我每当我按下下一步按钮时保留搜索值的方法。

我的Views.py文件

def coupons(request):
    search_filter = {}
    form = CouponSearchForm()
    if request.POST.get('active'):
        active = True if request.POST['active'] == 'true' else False
        search_filter['active'] = active
    if request.POST.get('marketing'):
        active = True if request.POST['marketing'] == 'true' else False
        search_filter['marketing'] = active
    if request.POST.get('coupon_code'):
        search_filter['code__icontains'] = request.POST.get('coupon_code')
    if request.POST.get('created_by'):
        if request.POST.get('created_by') in User.objects.all().values_list('username', flat=True):
            search_filter['created_by_id__username'] = User.objects.get(username=str(request.POST.get('created_by')))
        else:
            search_filter['created_by_id'] = int(0)
    if request.POST.get('language') and request.POST.get('language') != '':
        search_filter['language__pk'] = request.POST.get('language')
    if request.POST.get('package_id') and request.POST.get('package_id') != '':
        search_filter['package_id__pk'] = request.POST.get('package_id')
    if request.POST.get('email') and request.POST.get('email') != '':
        search_filter['email__icontains'] = request.POST.get('email')
    if request.POST.get('phone_number') and request.POST.get('phone_number') != '':
        search_filter['phone_number__icontains'] = request.POST.get('phone_number')
    if request.POST.get('exam_type') and request.POST.get('exam_type') != '':
        search_filter['exam_type__pk'] = int(request.POST.get('exam_type'))
    if request.POST.get('exam_name') and request.POST.get('exam_name') != '':
        search_filter['exam_name__exam_name'] = ExamName.objects.get(id=int(request.POST.get('exam_name'))).exam_name
    table = CouponTable(
        Coupon.objects.filter(**search_filter).order_by('-updated_at'))

    RequestConfig(request, paginate={"per_page": 30}).configure(table)

    return render(request, 'common/table.html', {'table': table, 'model': 'Coupon', 'url': 'add_coupon', 'form': form})

如您所见,搜索过滤器仅在第一页上起作用,但此后它失去了搜索过滤器的值,并且过滤不起作用。

0 个答案:

没有答案