在Django中搜索时分页不起作用

时间:2019-03-16 20:36:58

标签: python django

搜索时分页不起作用。

views.py

def crud(request):

    user_list = User.objects.all()
    paginator = Paginator(user_list, 3)
    page = request.GET.get('page')
    users = paginator.get_page(page)
    return render(request, 'crud/crud.html', {'users': users})


def search(request):

    users = None
    fname = request.POST.get('search')
    try:
        user_list = User.objects.filter(first_name__startswith=fname) | 
        User.objects.filter(last_name__startswith=fname)
        paginator = Paginator(user_list, 3)
        page = request.GET.get('page')
        users = paginator.get_page(page)
    except:
        pass
    return render(request, 'crud/crud.html', {'users': users}, {'fname': fname})

Crud.html

<form name="myform" method="POST" action="{% url 'search' %}">

{% csrf_token %}

         <input type="text" name="search" value="{{ fname }}" 

         placeholder="Search  name"/>

</form>

我该如何解决?

1 个答案:

答案 0 :(得分:0)

您无需尝试在Django中进行过滤。 结果是每次查询。

所以这应该很好,对我来说也很好:

users = None
fname = request.POST.get('search')
user_list = User.objects.filter(first_name__startswith=fname)
paginator = Paginator(user_list, 3)
page = request.GET.get('page')
users = paginator.get_page(page)
return render(request, 'crud/crud.html', {'users': users, 'fname': fname})