我为我的一个模型使用DateTimeField。它有一个custom validator,检查,没有日期将被接受。如何显示Django管理员中的DateTimeField的自定义验证错误?
如果我提供的日期在将来,错误会正确提出,但管理员显示Bitte eine Liste mit Werten eingeben.
(Enter a list of values.
)而不是我的验证错误消息。
我怎样才能让管理员显示我自己的验证错误信息呢?
这里是我的自定义验证(full source in this gist)的相关部分:
@deconstructible
class DateValidator():
# …
def __call__(self, value):
"""
Check *value* against the stored *date*.
If *date* is callable, it's return value is used, if not, it is used
directly.
"""
# get min/max date
try:
date = self.date()
except TypeError:
date = self.date
# check
if self.equal and value == date:
return
if self.after:
if value > date:
return
else:
if value < date:
return
raise ValidationError(
self.message, code='invalid', params={
'value': value.strftime(self.DATETIME_FORMAT),
'date': date.strftime(self.DATETIME_FORMAT)
}
)
我用它是这样的:
@python_2_unicode_compatible
class Article(models.Model):
# …
pub_date = models.DateTimeField(
'Veröffentlichungsdatum', blank=True, null=True,
validators=[DateValidator(timezone.now)],
help_text=("…")
)
将相关代码添加到帖子中wo uld有助于调试,特别是你如何调用验证器。 – Wolph