如何在Django管理员中显示DateTimeField的自定义验证错误?

时间:2022-04-29 23:19:22

I use a DateTimeField for one of my models. It has a custom validator, to check, that no dates from the future will be accepted.

我为我的一个模型使用DateTimeField。它有一个自定义验证器,用于检查未来的日期是否会被接受。

If I supply a date that lies in the future, the error is raised correctly but the admin shows Bitte eine Liste mit Werten eingeben. (Enter a list of values.) instead of my validation error message.

如果我提供将来的日期,则会错误地引发错误,但管理员会显示Bitte eine Liste mit Werten eingeben。 (输入值列表。)而不是我的验证错误消息。

How can I get the admin to show my own validation error message instead?

如何让管理员显示我自己的验证错误消息呢?

Here are the relevant parts of my custom validator (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)
      }
    )

And I use it like this:

我这样使用它:

@python_2_unicode_compatible
class Article(models.Model):

  # …

  pub_date = models.DateTimeField(
    'Veröffentlichungsdatum', blank=True, null=True,
    validators=[DateValidator(timezone.now)],
    help_text=("…")
  )

1 个解决方案

#1


1  

You can raise forms.ValidationError in forms.py Here is an example:

你可以在forms.py中引发forms.ValidationError这是一个例子:

class LoginForm(forms.Form):
    username = forms.CharField()
    password = forms.CharField(widget=forms.PasswordInput())

    def clean_username(self):
        username = self.cleaned_data.get("username")
        try:
            user = User.objects.get(username=username)
        except User.DoesNotExist:
            raise forms.ValidationError("Are you sure you are registered? We cannot find this user.")
        return username

#1


1  

You can raise forms.ValidationError in forms.py Here is an example:

你可以在forms.py中引发forms.ValidationError这是一个例子:

class LoginForm(forms.Form):
    username = forms.CharField()
    password = forms.CharField(widget=forms.PasswordInput())

    def clean_username(self):
        username = self.cleaned_data.get("username")
        try:
            user = User.objects.get(username=username)
        except User.DoesNotExist:
            raise forms.ValidationError("Are you sure you are registered? We cannot find this user.")
        return username