0

In my forms, if I have the following class with a field for my charfield 'bio'

class MyClass(forms.ModelForm):
    bio = forms.CharField(max_length=1000

Do I need to have the below validation or does the above max_length=1000 already cover that?

def clean_bio(self):
    bio=self.cleaned_data['bio']
    max_length = 1000
    if len(bio) > max_length:
        raise forms.ValidationError('Please limit your bio to 1000 words')
return bio
Micah Pearce
  • 1,805
  • 3
  • 28
  • 61

1 Answers1

1

It's not necessary at all to use it for the length, your model field has already a max_length, so Django will ensure that this value has less than 1000 characters.

NOTE: It's suggested that you use models.TextField() in models since your field can receive a great length of characters. Your form will be:

forms.CharField(max_length=1000,widget=forms.Textarea())
Lemayzeur
  • 8,297
  • 3
  • 23
  • 50
  • What does TextField do that CharField doesn't? Does it give error validation if it is longer? – Micah Pearce May 11 '18 at 01:59
  • Nm, I found this: https://stackoverflow.com/questions/7354588/django-charfield-vs-textfield – Micah Pearce May 11 '18 at 02:01
  • In case you use it in models as well, I'm just warning you to not use it for such field. Even in form, by using `forms.CharField`, you must use the widget `forms.Textarea()`, see my updated answer – Lemayzeur May 11 '18 at 02:09