python - Django admin 输入错误后出现错误消息

标签 python django django-admin

我想在 django admin 中添加对输入数据的验证,因此我已将此类代码添加到我的 models.py

class Score(models.Model):
  #fields description
    def save(self, *args, **kw):
        if (validating data):
            super(Score, self).save(*args, **kw)
        else:
            raise forms.ValidationError("Error input")

我无法理解必须在 ValidationError 中编写什么才能看到此消息。

最佳答案

您应该在 proper place 中执行此操作,而不是在保存

To assign exceptions to a specific field, instantiate the ValidationError with a dictionary, where the keys are the field names. We could update the previous example to assign the error to the pub_date field:

class Article(models.Model):
    ...
    def clean(self):
        # Don't allow draft entries to have a pub_date.
        if self.status == 'draft' and self.pub_date is not None:
            raise ValidationError({'pub_date': 'Draft entries may not have a publication date.'})
        ...

关于python - Django admin 输入错误后出现错误消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27450005/

相关文章:

python - 如何在 django admin 中显示其他模型的只读数据?

python - 在用户发送的 Django 管理页面中显示数据

python - Numpy 高级索引 : same index used multiple times in +=

python - 为什么 numpy.ravel 返回一个副本?

python - 大型文本文件中最快的文本搜索方法

python - 为什么我会收到 KeyError : 'scheduler' when trying to run a celery beat?

django - { "detail": "CSRF Failed: CSRF token missing or incorrect." }

python - 将 Django 表单字段更改为隐藏字段

django - 覆盖特定模型的 Django 管理 URL?

python - 如何将从缩放数据中学到的决策边界转移到原始数据(缩放数据)?