如何通过开始日期到结束日期过滤数据django然后在模板中显示数据

wxclj1h5  于 2023-01-14  发布在  Go
关注(0)|答案(1)|浏览(113)

models.py

class Income(models.Model):
    date = models.DateField()
    capital = models.IntegerField(null=True, verbose_name='Money Capital')
    revenue = models.IntegerField(null=True, verbose_name='Total Revenue')
    profit = models.IntegerField(null=True, verbose_name='Total Profit')

    def __str__(self):
        return self.profit

forms.py

from django import forms
from . models import Income

class DateChoiceField(forms.Form):
    date1 = forms.ModelChoiceField (
        queryset=Income.objects.values_list("date", flat=True).distinct(),
    )
    date2 = forms.ModelChoiceField (
        queryset=Income.objects.values_list("date", flat=True).distinct(),
    )

views.py

if request.method == "POST":
        form = DateChoiceField(request.POST)
        date1 = request.POST.get('date1')
        date2 = request.POST.get('date2')
        if 'form1' in request.POST:
            if form.is_valid():
                selectedDate1 = form.cleaned_data["date1"]
                selectedDate2 = form.cleaned_data["date2"]
                start = datetime(selectedDate1)
                end = datetime(selectedDate2)
                filterYearMonth = Income.objects.filter(date__gte=start).filter(date__lte=end)

            else:
                filterYearMonth = Income.objects.all()

    else:
        form = DateChoiceField()
        filterYearMonth = Income.objects.all()

context = {
    'filterYearMonth': filterYearMonth,
        'form': form,
}
return render (request, "dashboard/dashboard.html", context)

Jmeter 板. html

<form method="POST" action="/dashboard/">
            {% csrf_token %}
            {{ form }}
            <button type="submit" name="form1">Submit</button>
        </form>

        <h4>Filter</h4>
        <table>

            {% for item in filterYearMonth %}
            <tr>
                <td>{{ item.date }}</td>
                <td>{{ item.capital }}</td>
                <td>{{ item.revenue }}</td>
                <td>{{ item.profit }}</td>
            </tr>
            {% endfor %}

        </table>

我接近解决它,但它一直显示所有的数据,我得到这个“选择一个有效的选择。该选择不是可用的选择之一。”每当我尝试提交开始和结束日期。This is what it looks like

wgx48brx

wgx48brx1#

class DateChoiceForm(forms.Form):
    date1 = forms.ModelChoiceField (
        queryset=Income.objects.values_list("date", flat=True).distinct(),
    )
    date2 = forms.ModelChoiceField (
        queryset=Income.objects.values_list("date", flat=True).distinct(),
    )

ModelChoiceField期望您选择一个Model示例,但是您的查询集却给了它原始的日期来选择。因此,当您提交那些日期时,您的表单会变得混乱,而实际上它希望获得Incomes。ModelChoiceField查询集应该返回模型示例的查询集,而不仅仅是值。
但是我理解你为什么这样做,看起来你的表单用户并不关心"收入"的后端实现,他们只关心选择日期。
有一种方法可以将视图逻辑从后端逻辑中分离出来,您可以通过添加一个label_from_instance来实现这一点,该label_from_instance向用户显示日期,但会将与其关联的Income传递到后端Form,您可以通过创建一个自定义Field类来实现这一点。
比如:

class IncomeField(ModelChoiceField):
    def label_from_instance(self, obj):
        return obj.date

class DateChoiceField(forms.Form):
    income_1 = IncomeField(
        queryset=Income.objects.all().distinct(),
    )
    income_2 = IncomeField (
        queryset=Income.objects.all().distinct(),
    )

然后相应地调整您的FormView

相关问题