首页 > 解决方案 > django - 我如何使用来自选择表单的输入来比较我的数据库中的数据并将其输出到另一个页面上?

问题描述

<form method = "POST">
        {% csrf_token %}
        <div class = "lookback"
        <label for = "time"></label>
        <select name = "time" id = "time">
            <option value = "today">Today</option>
            <option value = "yesterday">Yesterday</option>
            <option value = "lastweek">Last Week</option>
            <option value = "lastmonth">Last Month</option>
            <option value = "lastyear">Last Year</option>
            <option value = "forever">Forever</option>
        </select>
            <button><a type= "button" class = "Look" id = "look" href = "">Look Back?!</a></button>
        </form> 

** 以上是我用来获取选择值的 HTML 页面部分,以便我可以在我的 views.py 中使用它来过滤数据并将其输出到另一个页面上。**

 def retro(request):
    if request.method == "POST":
        time = ThoughtForm(request.POST)
        today = timezone.now().date()
        if time == "Yesterday":
            yesterday = timezone.now().date() - timedelta(days=1)
            data = Thought.objects.filter(date__gte=yesterday, date__lt=today)
        elif time == "Last Week":
            week = timezone.now().date() - timedelta(days=7)
            data = Thought.objects.filter(date__gte=week, date__lt=today)
        elif time == "Last Month":
            month = timezone.now().date() - timedelta(days=30)
            data = Thought.objects.filter(date__gte=month, date__lt=today)
        elif time == "Last Year":
            year = timezone.now().date() - timedelta(days=365)
            data = Thought.objects.filter(date__gte=year, date__lt=today)
        elif time == "Forever":
            data = Thought.objects.all 
        else:
            data = Thought.objects.filter(date__gte=today, date__lt=today)
    
        return render(request,'look.html', {'data' : data})

    else:
        return render(request, 'retro.html')

当我使用 retro.html 的提交按钮(带有选择输入的那个)时,它确实将我引导到我想要将数据输出到的页面。但是,它不会打印页面中的数据。

<div class = "results">
    <form method = "GET" >
        <h1>Till now, you thought of writing- </h1>
        <table class="table">
            <thead class = "thead-dark">
                <tr>
                    <td>Thought</td>
                    <td>Date</td>
                </tr>
            </thead>
            <tbody>
                {% for obj in data%}     
                <tr>
                    <td scope="row">{{ obj.thought }}</td>
                    <td>{{ obj.date.date}}</td>
                </tr>
                {% endfor %}

正上方是我试图在其中输出数据的页面的 html。

from django.db import models
from django.utils import timezone
# Create your models here.

class Thought(models.Model):
    thought = models.CharField( max_length=300)
    done = models.BooleanField(default = False)
    #date = models.models.DateField()
    date = models.DateTimeField(default=timezone.now)

    def __str__(self):
        return str(self.thought) + "-  " + str(self.done)

正上方是我的 models.py 文件。

from django import forms 
from retrospection.models import Thought

class ThoughtForm(forms.ModelForm):
    class Meta:
        model = Thought
        fields = ['thought', 'done', 'date']

正上方是我的 form.py 文件。

在尝试了 Blackeagle52 的建议并通过打印 (form.is_valid()) 后,我发现我的表单未能通过 is_valid 测试并出现错误 -

<ul class="errorlist"><li>thought<ul class="errorlist"><li>This field is required.</li></ul></li><li>date<ul class="errorlist"><li>This field is required.</li></ul></li></ul>

我的表单包含一个带有几个选项的选择项和一个提交按钮。我不确定该字段如何为空。请帮我。

标签: pythondjangoselect

解决方案


def retro(request):
    if request.method == "POST":
        form = ThoughtForm(request.POST)
        if form.is_valid():
            time = form.cleaned_data['time']
            today = timezone.now().date()
            if time == "Yesterday":
                yesterday = timezone.now().date() - timedelta(days=1)
                data = Thought.objects.filter(date__gte=yesterday, date__lt=today)
            elif time == "Last Week":
                week = timezone.now().date() - timedelta(days=7)
                data = Thought.objects.filter(date__gte=week, date__lt=today)
            elif time == "Last Month":
                month = timezone.now().date() - timedelta(days=30)
                data = Thought.objects.filter(date__gte=month, date__lt=today)
            elif time == "Last Year":
                year = timezone.now().date() - timedelta(days=365)
                data = Thought.objects.filter(date__gte=year, date__lt=today)
            elif time == "Forever":
                data = Thought.objects.all 
            else:
                data = Thought.objects.filter(date__gte=today, date__lt=today)
    
            return render(request,'look.html', {'data' : data})
        # TODO Do something when form is invalid.
        #      Maybe just removing the else below this, so you'll get retro.html
    else:
        return render(request, 'retro.html')

为了解释我的解决方案,您的代码time中不是一个值,而是一个表单。要从表单中检索数据,您首先需要检查表单是否有效 ( is_valid()),然后从 中检索值form.cleaned_data

还有一些其他的小事情你可以改进。在 POST 之后,重定向到另一个视图,因为现在这个 look.html 仅在 POST 上可见。如果您想刷新该页面或其他内容,您将返回retro.html。

使用 Forever-case 时,您也不会()接听.all()电话。


推荐阅读