将表单中的日期字段与当前日期进行比较

时间:2017-11-14 12:25:24

标签: django

如果表单中输入的日期在当前日期之前,我试图用if语句检查。如果是这样写入模型中的对象。我也不确定是否有更好的方法。

我收到此错误

'<' not supported between instances of 'DateField' and 'datetime.date'

我的观点:

class ActionCreateView(LoginRequiredMixin, generic.CreateView):
    login_url = '/scrty/login/'
    template_name = "nodiso/actioncreate.html"
    form_class = forms.LeadActionCreateForm
    # success_url = reverse_lazy('nodisoapp:leaddetail', kwargs['pk'] )

  def get_success_url(self, **kwargs):
    return reverse("nodisoapp:leaddetail", kwargs={'pk': 
    self.kwargs['pk']})

  def form_valid(self, form):
     if form.fields['Duedate'] < datetime.date.today():
        self.object.overdue = 1
    else:
        pass
    self.object = form.save(commit=False)
    self.object.lead_id = self.kwargs['pk']
    self.object.creator = self.request.user.firstname
    self.object.save()
    return super(ActionCreateView, self).form_valid(form)

型号:

class LeadActions(models.Model):
    lead = models.ForeignKey(Leads)
    name = models.CharField(max_length=265)
    crdate = models.DateField(auto_now_add=True)
    Duedate = models.DateField()
    creator = models.CharField(max_length=265)
    overdue = models.IntegerField(null=True,blank=True)

  def __str__(self):
    return self.name

表格:

class LeadActionCreateForm(forms.ModelForm):
    class Meta:
        model = models.LeadActions
        fields = ['name','Duedate']

1 个答案:

答案 0 :(得分:1)

由于您已从此处的表单中提取未保存的模型:

self.object = form.save(commit=False)

为什么不直接从模型实例中读取Duedate,并相应地设置overdue标志?

is_overdue = self.object.Duedate > datetime.date.today()
self.object.overdue = 1 if is_overdue else None

完整代码:

class ActionCreateView(LoginRequiredMixin, generic.CreateView):
     login_url = '/scrty/login/'
     template_name = "nodiso/actioncreate.html"
     form_class = forms.LeadActionCreateForm
     # success_url = reverse_lazy('nodisoapp:leaddetail', kwargs['pk'] )

     def get_success_url(self, **kwargs):
          return reverse("nodisoapp:leaddetail", kwargs={'pk': self.kwargs['pk']})

     def form_valid(self, form):
         self.object = form.save(commit=False)
         is_overdue = self.object.Duedate > datetime.date.today()
         self.object.overdue = 1 if is_overdue else None

         self.object.lead_id = self.kwargs['pk']
         self.object.creator = self.request.user.firstname
         self.object.save()
         return super(ActionCreateView, self).form_valid(form)