1

I have a model named Comments which has content=models.CharField(max_length=100) in forms I want to use "def clean_content" to raise validation error if user types characters exceeding max_length. So how to use if condition operator.

def clean_content(self):
    content = self.cleaned_data.get("content")
    if ????????? < 100:
        return content
    else:
        raise forms.ValidationError(('You exceeded max number of character'))
tepeholm
  • 66
  • 1
  • 6

1 Answers1

0

Short answer: Django will normally handle the max_length constraint for you, no need to validate this yourself.

You can check the length of the content, for example with:

def clean_content(self):
    content = self.cleaned_data.get('content')
    if len(content) <= 100:
        return content
    else:
        raise forms.ValidationError('You exceeded max number of character')

But you do not need to implement this validation yourself. Django's ModelFrom will automatically check the max_length of the field, and in case the number exceeds that, it will raise an error. For example:

>>> form.errors
{'content': ['Ensure this value has at most 100 characters (it has 1000).']}

so you do not need to validate this yourself.

Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555
  • Just now realized that in my other apps it handles itself. The problem was with my one app. Still dont know what is the problem. Thanks Willem at least learned how to handle condition. One more question how to format that error in template (color, size, etc.) – tepeholm Sep 04 '19 at 20:47
  • @tepeholm: you can specify a css class, and then add some css styling: https://stackoverflow.com/q/4847913/67579 – Willem Van Onsem Sep 04 '19 at 20:52
  • sorry , one more question. how error message class is called in template? – tepeholm Sep 04 '19 at 21:16
  • @tepeholm: you set that in the form as `error_css_class` (as class attribute), see linked question. – Willem Van Onsem Sep 04 '19 at 21:16