我有一个带有DateTimeField模型的Django表单,我想知道是否有办法确保用户输入的日期/时间总是大于当前时间。
这就是我的形式:
from django.db import models
from django import forms
import datetime
start_time = models.DateTimeField(
default=datetime.datetime.now(),
help_text='Format is: yyyy-mm-dd hh:mm:ss',
)
答案 0 :(得分:3)
将此添加到您的模型中。
from django.core.exceptions import ValidationError
from django.db import models
class MyModel(models.Model):
# ...
# extend the validation
def clean(self, *args, **kwargs):
# run the base validation
super(MyModel, self).clean(*args, **kwargs)
# Don't allow dates older than now.
if self.start_time < datetime.datetime.now():
raise ValidationError('Start time must be later than now.')