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.
you can change field attributes at runtime, in the
__init__
method.