Reputation: 5010
I've a model like this:
class Message(models.Model):
msg = models.CharField(max_length = 150)
and I have a form for insert the field. Actually django allows empty spaces, for examples if I inset in the field one space it works. But now I want to fix this: the field is not required, but if a user insert a spaces, the validation should fail.
I've added:
class Message(models.Model):
msg = models.CharField(max_length = 150, blank = False)
but it doesn't work. What's the mistake?
Upvotes: 8
Views: 4486
Reputation: 38392
Whitespace is not considered to be blank. blank specifically refers to no input (i.e. an empty string ''
). You will need to use a model field validator that raises an exception if the value only consists of spaces. See the documentation for details.
Example:
def validate_not_spaces(value):
if isinstance(value, str) and value.strip() == '':
raise ValidationError(u"You must provide more than just whitespace.")
class Message(models.Model):
msg = models.CharField(max_length=150, blank=False,
validators=[validate_not_spaces])
Upvotes: 13
Reputation: 53998
You need to create your own form and perform custom validation on the field to make sure that repeated spaces are raised as a validation error. Something like this:
import re
class MessageForm(form.ModelForm)
def clean_msg(self):
msg = self.cleaned_data['msg']
if re.match('/[\s]+$',msg):
raise ValidationError("Spaces not allowed")
return msg
Upvotes: 1