Django:Model函数未在模板中返回正确的值

时间:2019-05-09 11:20:45

标签: django django-templates django-views

拥有bookingrecordsView视图,在该视图中我提取了用户的所有保留。我添加了一个模型函数is_pending(),该函数可获取预留实例,检查date_to字段是否已通过,并返回一个字符串。获取预留的视图:

def bookingrecordsView(request):
     rsv = Reservation.objects.filter(user=request.user)
     return render(request, 'booking_history_page.html', {'rsv': rsv})

以及检查日期的功能:

class Reservation (models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    date_from = models.DateField(auto_now=False, auto_now_add=False, blank=False)
    date_to = models.DateField(auto_now=False, auto_now_add=False, blank=False)
    time_from = models.TimeField(auto_now=False, auto_now_add=False, blank=False)
    time_to = models.TimeField(auto_now=False, auto_now_add=False, blank=False)
    destination=models.CharField(max_length=20, blank=False, verbose_name="Where will you go")
    chosen_vehicle=models.CharField(max_length = 20, blank=False, default='')
    booking_time=models.DateTimeField(default = datetime.now)
    garage = models.CharField(max_length = 20)
    city = models.CharField(max_length = 20, default='')
    area = models.CharField(max_length = 20, default='')

    @property
    Def is_pending(self):
        if self.date_to < datetime.date.today():
             return "Pending"
        else:
            return "Over"`

这是我的模板片段:

{% for r in rsv %}
     <tr>
         <td>{{ r.id }}</td> 
         <td>{{ r.date_from }} - {{ r.date_to }}</td>
         <td>{{ r.time_from }} - {{ r.time_to }}</td>
         <td>{{ r.chosen_vehicle }}</td>
         <td>{{ r.garage }}</td>
         <td>{{ r.destination }}</td>
         <td>{{ r.is_pending }}</td>
      </tr>
 {% endfor %}`

现在,对于所有预订,即使是几个月前通过的预订,此状态始终返回“待处理”。

如何从Reservation函数为每个is_pending()实例获取正确的返回值,并将其相应地传递给模板?

0 个答案:

没有答案