解决 Django 中分页错误:Key ‘userchoice‘ not found in <QueryDict: {}>

在 Django 项目中,使用分页功能时遇到了一个错误:Key 'userchoice' not found in <QueryDict: {}>.

分页限制了要正确显示的数据,但当我点击“下一页”时,它会显示错误。问题似乎出在当我单击“下一页”时,无法找到最初的搜索条件,从而导致错误。

解决方案

经过分析,发现错误的原因是使用了 POST 方法来提交表单,但创建分页链接时却使用了 GET 方法,然后又在这些 GET 链接中添加了页码。这导致 Django 无法找到最初的搜索条件,因为它们没有包含在 POST 数据中。

为了解决这个问题,需要使用 GET 方法来提交原始搜索请求,并将相同的变量包含在所有分页链接中,只需替换页码即可。通过修改提交表单的方法,就可以在提交搜索条件时使用 GET 方法,同时在创建分页链接时也使用 GET 方法,将原始的搜索条件作为参数传递给分页链接。

代码示例

# views.py
def testeruser(request):
    if request.method == 'GET':
        getchoice = request.GET.get('userchoice')
        getfirstdate = request.GET.get('firstdate')
        getseconddate = request.GET.get('seconddate')
    elif request.method == 'POST':
        # Handle the form submission and redirect to the GET endpoint with the search parameters
        return redirect('testeruser', userchoice=request.POST['userchoice'], firstdate=request.POST['firstdate'], seconddate=request.POST['seconddate'])

    # Get the data based on the search parameters
    getdata = applicationform.objects.filter(date__gte=getfirstdate , date__lte=getseconddate)

    # Create the pagination object
    searchpagination = Paginator(getdata, 3)

    # Get the current page number from the request
    page = request.GET.get('searchpage')

    # Get the current page of results
    try:
        searchcontacts = searchpagination.page(page)
    except PageNotAnInteger:
        searchcontacts = searchpagination.page(1)
    except EmptyPage:
        searchcontacts = searchpagination.page(searchpagination.num_pages)

    # Render the search page with the data and pagination information
    return render_to_response('registration/search_page.html', {
    
    'getdata': getdata, 'getchoice': getchoice, 'searchcontacts': searchcontacts})

自定义模板

<!-- search_page.html -->
<form method="GET" action="/testeruser/" class="form-horizontal" name="searchform" enctype="multipart/form-data">
    {% csrf_token %}
    <select name="userchoice" id="client_specification" class="span2" required>
        <option value='-1'>Select Your Choice</option>
        <option value='0'>Biddings</option>
        <option value='1'>Interviews</option>
        <option value='2'>Jobs</option>
    </select>
    From: <input type="text" class="input-xlarge" name="firstdate" id="search1" readonly="readonly" />
    To: <input type="text" class="input-xlarge" name="seconddate" id="search2" readonly="readonly" />
    <button class="btn btn-gebo" type="submit" name="asubmit">Submit</button>
</form>

<!------------ PAGINATION---------------->
<div class="pagination">
    <ul>
        {% if searchcontacts.has_previous %}
            <li><a href="?userchoice={
     
     { getchoice }}&firstdate={
     
     { firstdate }}&seconddate={
     
     { seconddate }}&searchpage={
     
     { searchcontacts.previous_page_number }}">PREVIOUS</a></li>
        {% endif %}

        {% if searchcontacts.has_next %}
            <li><a href="?userchoice={
     
     { getchoice }}&firstdate={
     
     { firstdate }}&seconddate={
     
     { seconddate }}&searchpage={
     
     { searchcontacts.next_page_number }}">NEXT</a></li>
        {% endif %}
    </ul>
</div>
<!------------ PAGINATION---------------->

通过这些修改,当用户提交搜索条件时,会使用 GET 方法,并将搜索条件作为参数传递给分页链接。单击“下一页”时,分页链接将包含原始的搜索条件,从而避免错误。