Reputation: 5355
In Django, say I have a User field and I want to change the "this user alread exist" error message. I know I can parse a dictionary in e.g forms.py
like
class MyForm(Form):
.
.
.
error_messages={"unique": ("Wups, enter a unique username")}
but it requires I know the key/value pair, which might not always be obvious what the key is.
Is there a way (in the Django documentation it seems pretty scattered) where these error-message key/value pairs are, or what is the most easy way to find those?
Upvotes: 1
Views: 727
Reputation: 2402
the common ones are as
'null': 'This field cannot be null.'
'blank': 'This field cannot be blank.'
'invalid' : 'Enter a valid email address.'
'invalid_choice': 'Value is not a valid choice.'
'required': 'This field is required.'
'max_length': '...'
'min_length': '...'
'max_value': '...'
'min_value': '...'
'max_digits': '...'
'invalid_list': '...'
'max_decimal_places': '....'
'empty': '....'
...
and with any other error message you face and don't know the type you can simply do a form.errors.as_json()
it will return you the errors as
{
"sender": [{"message": "Enter a valid email address.", "code": "invalid"}],
"subject": [{"message": "This field is required.", "code": "required"}],
}
then that you could use the code as key
and the write your message for it.
Upvotes: 3
Reputation: 20539
You can find all the error messages for particular field types on this page of the Django documentation. For each field type there is an Error message keys
specified.
You can also look for the code of the field you want to use and there should be a default_error_messages
specified either directly or in its ancestors. Look through all of them for all the error messages you can overwrite.
Upvotes: 0
Reputation: 16666
All messages in Django - including the error messages you want to change - are translated, and stored in translation files (*.po extension). You can override only these files, and Django will then use your version for whichever languages you support.
Read more on translations in general for Django: https://docs.djangoproject.com/en/3.1/topics/i18n/ https://docs.djangoproject.com/en/3.1/topics/i18n/translation/
Read on creating translation files: https://docs.djangoproject.com/en/3.1/topics/i18n/translation/#localization-how-to-create-language-files
To dump all translations, it might work to add the JavaScriptCatalog
or the JsonCatalog
that come with Django to your urls.py
as described here: https://docs.djangoproject.com/en/3.1/topics/i18n/translation/#module-django.views.i18n
This will include all translations for all apps listed in INSTALLED_APPS unless you restrict it.
Upvotes: 0