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?
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])
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With