Django 1.4 - Add custom error message to user fields in form with meta field Model=User
-
02-06-2021 - |
Question
I was trying to add some custom error messages to a form like this one:
class RegistrationForm(forms.ModelForm):
class Meta:
model = User
fields = ('email',)
extra_field = forms.CharField(error_messages={
'required':'Este campo es requerido'
})
I have no problem adding custom error messages to a field that is declared in the form (extra_field
), but I'm having trouble adding custom error messages to the fields inherited from the model User
via meta
class (email
).
What I really want is to customize all the error messages of this form. Also, I would like to display them in spanish, not english.
So far I have not found any documentation about how to customize the form fields inherited from the model User, I don't really want to write a new form just because of the error messages.
Thanks in advance!!!
PD: I'm using Django 1.4 and python 2.6.6 in a debian squeeze box.
Solution
Ok guys, thank you all for your answers, in fact you helped me a lot!!!
I solved the problem like this:
Suposse I have this form:
class RegistrationForm(forms.ModelForm):
class Meta:
model = User
fields = ('username', 'email')
And I want to add custom error messages to the username field, but I don't want to loose all the validation that already comes with that field.
I added this method to my RegistrationForm class:
def clean_username(self):
data = self.cleaned_data
# My extremely important validation.
if len(data['username']) == 5:
self.fields['username'].error_messages["myerror"] = "The important message"
raise forms.ValidationError(self.fields['username'].error_messages["myerror"])
return data['username']
The advantage of this aproach is that I don't loose the other validation checks that already come with the field in question.
This is important because now I don't have to validate that the user already exists in my database.
Thanks for your responses, have a good day!!!
OTHER TIPS
Turn on internalization in your settings.py
USE_I18N = True
LANGUAGE_CODE = 'es'
Model User
doesn't differ from others. Put your code to figure out the issue.
In your meta class fields = ('email')
must be tuple or list, i.e. fields = ('email', )
You can override any of the inherited fields by simply redefining them in exactly the same way as you have defined your extra field.