gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-30 01:30:53 25 4
gpt4 key购买 nike

我正在尝试更改 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com