简体   繁体   中英

python django_tables2 filtering and pagination issue

I am trying to render a web page with a table of filtered data. The filtering should be based on a date submitted by the user. For the initial GET request I have tried setting an initial_date of '01 01 2015' and when a POST request is submitted, the date is extracted form the POST query-set.

The issue I am having appears to be related to django_tables2 pagination. The initial table data is successfully rendered after the user submits the date form in the POST request, however when I click the "Next" button on the bottom of the table I receive "Exception Value: That page contains no results".

Clicking the Next button appears to call the GetCustomData() function as a GET request, which then uses the "initial_time" rather than the filtered data.

How do I format my function so that subsequent GET requests return the filtered data from the initial POST request?

views.py

from django.shortcuts import render
from .models import TestResult
import datetime
import django_tables2 as tables
from .forms import DateForm

class SimpleTable(tables.Table):
    class Meta:
        model = TestResult
        attrs = {"class": "paleblue"}


def GetCustomData(request):

    form = DateForm()

    if request.method == 'POST':
        request_time = datetime.datetime.strptime((request.POST['custom_date_day']+' '+request.POST['custom_date_month']+' '+request.POST['custom_date_year']), '%d %m %Y')
        time_min = datetime.datetime.combine(request_time, datetime.time.min)
        time_max = datetime.datetime.combine(request_time, datetime.time.max)
        custom_query = TestResult.objects.filter(timestamp__range=(time_min, time_max))
        table = SimpleTable(custom_query)
        table.paginate(page=request.GET.get('page', 1), per_page=30)

        return render(request, 'custom_results.html', {'table_results': table,
                                                       'form': form})

    elif request.method == 'GET':
        initial_time = datetime.datetime.strptime('01 01 2015', '%d %m %Y')
        time_min = datetime.datetime.combine(initial_time, datetime.time.min)
        time_max = datetime.datetime.combine(initial_time, datetime.time.max)
        custom_query = TestResult.objects.filter(timestamp__range=(time_min, time_max))
        table = SimpleTable(custom_query)
        table.paginate(page=request.GET.get('page', 1), per_page=30)

        return render(request, 'custom_results.html', {'table_results': table,
                                                       'form': form})

可能不是最干净的方法,但是我设法通过引用和更新GetCustomData()函数外部的列表来使其工作。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM