也许试试这个Model.clean()
方法。这将ValidationError
在正确的位置引发 s(将在管理员中显示表单错误而不是 500)。
只有当它是现有记录并且到期日期未更改时,clean 方法才允许将到期日期保存在过去。
from datetime import datetime
from django.core.exceptions import ValidationError
class MyModel(models.Model)
expires = models.DateTimeField()
def __init__(self, *args, **kwargs):
super(Game, self).__init__(*args, **kwargs)
self.__old_expires = self.expires
def clean(self):
" Make sure expiry time cannot be in the past "
if (not self.id or self.__old_expires != self.expires)
and self.expires <= datetime.now():
raise ValidationError('MyModel entries cannot expire in the past.')
文档:https ://docs.djangoproject.com/en/dev/ref/models/instances/#django.db.models.Model.clean