Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django - how to set blank = False, required = False

Tags:

python

django

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?

like image 825
Fred Collins Avatar asked Jun 01 '11 00:06

Fred Collins


2 Answers

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])
like image 128
bradley.ayers Avatar answered Oct 13 '22 04:10

bradley.ayers


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
like image 31
Timmy O'Mahony Avatar answered Oct 13 '22 03:10

Timmy O'Mahony