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.

Figured it out. Just adding description = forms.RegexField(regex=r'[^(\s+)]') to class ItemForm will cause the form.is_valid() to fail and show the error

class ItemForm(ModelForm):
    description = forms.RegexField(regex=r'[^(\s+)]')
    class Meta:
        model = Item

To include your own message, add error_message=... to forms.RegexField

description = forms.RegexField(regex=r'[^(\s+)]', error_message=_("Your error message here."))

why regex? just use str.strip() to check if a string consists of only whitespace

Need Your Help

Is there a way to speed up GetAccessControl and GetOwner

c# performance

I'm going through a lot of files and on each file I need to obtain owner sid and owner ntaccount. I do this by using GetAccessControl() and GetOwner() which works great, exception for one thing. It's

Exception handling loop puzzle

c# .net exception exception-handling

I recently encountered a behavior that I've never seen before. I cannot quite understand what's going on most likely due to lack of fundamental knowledge with regards to the inner workings Exception