<p>您希望同时验证<code>lesson_datetime_start</code>和<code>lesson_datetime_end</code>,而不是单独验证。只是检查一下时间是否不超过11:59pm并不能缩短它,因为这会使2019-05-04 11:00pm-2019-05-05 12:00am无效,即使它是从晚上11点开始的一个小时的正确间隔。你知道吗</p>
<p>为此,请在窗体中添加<code>clean()</code>方法:</p>
<pre><code>def clean(self):
cleaned_data = super().clean()
if self.cleaned_data.get('lesson_datetime_start') \
and self.cleaned_data.get('lesson_datetime_end') \
and self.cleaned_data['lesson_datetime_start'] >= self.cleaned_data['lesson_datetime_end']:
raise ValidationError({'lesson_datetime_end': "End time must be later than start time."})
return cleaned_data
</code></pre>
<p>以同样的方式,您可以通过减去两个<code>datetime</code>字段并将它们与<code>datetime.timedelta(hours=x)</code>进行比较,来添加一个验证程序,说明课程的持续时间不超过某个预期的时间间隔(例如,不能长于4小时)。你知道吗</p>
<p>您也可以在模型中执行此操作,因此假设您有一个带有字段<code>lesson_start</code>和<code>lesson_end</code>的<code>Lesson</code>模型:</p>
<pre><code>def clean(self):
if self.lesson_start and self.lesson_end and self.lesson_start >= self.lesson_end:
raise ValidationError({'lesson_end': "End time must be later than start time."})
</code></pre>