Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 961
X10 Avatar asked Dec 17 '25 16:12

X10


1 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.

like image 82
Carl Meyer Avatar answered Dec 20 '25 07:12

Carl Meyer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!