What is the best way to catch and show an error if user enters only whitespace in a form field in Django?
In Django 1.0, what is the best way to catch and show an error if user enters only whitespace (" ") in a form field?
class Item(models.Model): description = models.CharField(max_length=100) class ItemForm(ModelForm): class Meta: model = Item
if user enters only whitespace (" ") in description CharField, what change needs to done to class Item or class ItemForm so that form.is_valid() fails and shows an error?
After form.is_valid(), I could write the code to check for only whitespaces in description field and raise a validation error but there has to be a better way. Can RegexField be used to specify description entered should not be just whitespaces. Any suggestions?
class ItemForm(forms.ModelForm): class Meta: model = Item def clean_description(self): if not self.cleaned_data['description'].strip(): raise forms.ValidationError('Your error message here')
The forms validation documentation might provide a good read.