python - 如何覆盖模板中的 ArrayField 默认错误消息?

标签 python django postgresql

我正在尝试更改 Django 为 ArrayField 生成的默认错误消息(特别是输入了太多项的错误消息)

如果用户在我的 ArrayField 中输入了太多项目,则会在模板中生成以下消息:

List contains 4 items, it should contain no more than 3.

我想把这条消息改成

You can't have more than 3 topics.

我尝试将以下错误消息添加到我的 forms.py TopicForm 元类中,但没有成功

    error_messages = {
        'topic': {
            'invalid': ("You can't have more than 3 topics."),
        },

这是我的 models.py 文件

from django.contrib.postgres.fields import ArrayField
from django.db import models

class Topic(models.Model)
    topic = ArrayField(models.CharField(max_length=20), size=3, blank=True,    null=True)

和我的forms.py

from django import forms
from .models import Topic

class TopicForm(forms.ModelForm):
    class Meta:
        model = Topic

        fields = ['topic']

希望对此有一些意见!谢谢!

最佳答案

ArrayField 有多个错误“代码”来处理各种类型的用户输入。

元素过多的数组的错误“代码”是max_length

这是重写的代码,包含您遗漏的部分 :)

error_messages = {
    'topic': {
        'max_length': ("You can't have more than 3 topics."),
     },

顺便说一下,当用户尝试提交不完整的输入时,您可能还想自定义您的 item_invalid 错误消息。

例如尝试提交 string1,string2,(看到多余的逗号了吗?) 将提高:

Item 3 in the array did not validate

您可以通过添加自定义 item_invalid 消息:

error_messages = {
        'topic': {
            'max_length': ("You can't have more than 3 topics."),
            'item_invalid': ("Your customized message"),
         },

关于python - 如何覆盖模板中的 ArrayField 默认错误消息?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55684952/

相关文章:

sql - PostgreSQL 计算子字符串在文本中出现的次数

c++ - 导入 .so 时导入语句的顺序是否重要?

python - 按 Pandas 中的多个日期对数据进行分组

python - LLVM、Parrot、JVM、PyPy + python

django - 如何在列表显示表单上添加自定义验证

python - 带有 to_field 属性的 Django 外键字段的问题

sql - 使用 random() 的子查询中集合返回函数的不一致行为

python - 在 python 中使用 numpy 时出现 "shape mismatch"错误

python - Django:无法将空表单字段保存到数据库 - 基数为 10 的 int() 的无效文字: ''

Postgresql 奇怪的索引大小