Django,Models&表单:替换“此字段是必需的”信息 [英] Django, Models & Forms: replace "This field is required" message

查看:147
本文介绍了Django,Models&表单:替换“此字段是必需的”信息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道如何在使用普通的Django表单时设置自己的自定义错误消息。但是,基于现有模型的Django Form呢?考虑以下模型和形式:

I know how to set my own custom error messages when using ordinary Django Forms. But what about Django Form based on an existing model? Consider following model and form:

Class MyModel(models.Model):
    name = models.CharField(max_length='30')

Class MyForm(forms.ModelForm):
    Class Meta:
        model = MyModel

如果我创建这样的表单并尝试发布,则显示此字段为必需消息。但是怎么改呢?当然我可以这样做:

If I create such form and try to post it, message "This field is required" appears. But how to change it? Of course I could do something like this:

Class MyForm(forms.ModelForm):
    model = forms.CharField(error_messages = {'required': "something..."})
    Class Meta:
        model = MyModel

但是根据文档,max_length属性将不会被保留,我必须将其明确写入表单定义。我认为模型表单的目的是避免编写相同的代码两次。因此,必须有一些简单的方法来更改自定义错误消息,而无需重写整个表单。如果我的消息看起来像字段名称是必需的,那么基本上这将是足够的。

But according to the documentation, max_length attribute won't be preserved and I have to write it explicitly to the form definition. I thought that the purpose of Model Forms is to avoid writing the same code twice. So there has to be some easy way to change the custom error message without rewriting the whole form. Basically it would be enough for me if my message looked something like "The field 'name' is required".

请帮助。

推荐答案

class MyForm(forms.ModelForm):
    class Meta:
            model = MyModel

    def __init__(self, *args, **kwargs):
        super(MyForm, self).__init__(*args, **kwargs)
        self.fields['name'].error_messages = {'required': 'custom required message'}

        # if you want to do it to all of them
        for field in self.fields.values():
            field.error_messages = {'required':'The field {fieldname} is required'.format(
                fieldname=field.label)}

这篇关于Django,Models&表单:替换“此字段是必需的”信息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆