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?

Answers


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.


Need Your Help

IBM Worklight 6.0 - QR Code does not work

iphone worklight qr-code worklight-mbs

I am trying to open hybrid app in my iphone, so the best option for me is scan in a QR code that I can save time to input long URL. But what makes me so upset is that the icon fails to open in a new

Security Issue: when using jQuery with json to request from service

jquery json

if you are calling a service using jQuery like below, in this case your service call is shown and displayed to the user that allow him to call such service using fiddler or any custom web applicati...