Django, Models & Forms: replace “This field is req

2020-01-31 02:39发布

问题:

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

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".

Please help.

回答1:

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)}


回答2:

you can change field attributes at runtime, in the __init__ method.



标签: django forms