Jamie Forrest
Jamie Forrest

Reputation: 11113

Django - Change the max_length error message on a CharField TextInput

I am trying to customize the error message displayed when a user inputs text longer than the max length for a CharField in my model. The model defines the field as follows:

name = models.CharField(max_length=200)

I have a ModelForm for this model that defines the form field as follows:

name = forms.CharField(widget=forms.TextInput(attrs={'class':"span8", 'placeholder':'e.g. How do I setup a wi-fi network? How to sync my iPhone with iCloud?'}),
                            error_messages={'required': 'Please enter a question.', 'max_length': 'Your question is too long.'})

This works fine for the 'required' error message, but the 'max_length' error message still uses Django's default message here. Am I doing something wrong or should this text be customized in some other way?

Upvotes: 1

Views: 5732

Answers (3)

MOHRE
MOHRE

Reputation: 1156

You can create subclass of 'django.core.validators.MaxLengthValidator'

from django.core.validators import MaxValueValidator

class MyValidator(MaxValueValidator):
    message = 'Your question is too long.'

Upvotes: 0

rtbortolin
rtbortolin

Reputation: 93

I'm not sure from which version it is working, but now you can do this:

class YouForm(forms.ModelForm):

     def __init__(self, *args, **kwargs):
         self.fields['you_field'].error_messages = {'max_length': 'Ensure this value has at most %(limit_value)d character (it has %(show_value)d).'}

Upvotes: 3

okm
okm

Reputation: 23871

The 'max_length' is checked by 'django.core.validators.MaxLengthValidator', which has hard-coded error message. You could replace it w/ your own version by:

# after the name or ModelForm definition
name.validators[-1].message = 'Your question is too long.'

Upvotes: 3

Related Questions