views:

81

answers:

2

I can see how to add an error message to a field when using forms, but what about model form?

This is my test model

class Author(models.Model):
    first_name = models.CharField(max_length=125)
    last_name = models.CharField(max_length=125)
    created = models.DateTimeField(auto_now_add=True)
    updated = models.DateTimeField(auto_now=True)

My model form

class AuthorForm(forms.ModelForm):
    class Meta:
        model = Author

The error message on the fields: first_name, and last_name is "This field is required". How do I change that in a model form?

A: 

the easyest way is to override the clean method:

class AuthorForm(forms.ModelForm):
   class Meta:
      model = Author
   def clean(self):
      if self.cleaned_data.get('name')=="":
         raise forms.ValidationError('No name!')
      return self.cleaned_data
Mermoz
+2  A: 

For simple cases, you can specify custom error messages

class AuthorForm(forms.ModelForm):
    first_name = forms.CharField(error_messages={'required': 'Please let us know what to call you!'})
    class Meta:
        model = Author
chefsmart
Cool thanks. I did not know what would be the result of doing that. The documentation says "Declared fields will override the default ones generated by using the model attribute" so I should be good. I would also have to set the max_field again on the model form field.
iHeartDucks