Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django CharField without empty strings

Tags:

python

django

Is there any way to make a CharField (or TextField) that doesn't accept empty strings? I'm trying to use blank=False but it's not working...

class Foo(models.Model):
    title = models.CharField(max_length=124, blank=False)

Then after syncdb I run python manage.py shell, and I can type:

f = Foo()
f.save()

and it doesn't complain. The object has a title with a value ''. I don't want this to happen, I want it to complain if Foo() isn't explicitly given a non-empty string. Any way to do this?

I'm using Django 1.6

like image 211
antimatter Avatar asked Mar 26 '14 03:03

antimatter


2 Answers

Use a MinLengthValidator:

from django.core.validators import MinLengthValidator
...
title = models.CharField(max_length=10, validators=[MinLengthValidator(1)])
like image 150
Babken Vardanyan Avatar answered Nov 10 '22 04:11

Babken Vardanyan


According to the documentation, blank=False is purely validation-related that works only on a form level.

See related threads:

  • Django model blank=False does not work?
  • Why are blank and null distinct options for a django model?
like image 4
alecxe Avatar answered Nov 10 '22 05:11

alecxe