Does model.CharField ('blank = False') work with save ()?

I have a model like this with Django 1.1:

class Booking(models.Model): name = models.CharField(max_length=100) 

By default, I read that both "null" and "blank" are False.

So, with a test like this ...

 class SimpleTest(TestCase): def test_booking_save(self): b = Booking() b.save() 

... I expected to keep throwing an exception. But this is not so. It seems quite happy to create a new entry with an empty name (Postgres and SQLite3).

I note that through the admin interface, the failure does indeed occur with a "required field".

Questions:

  • Is the 'blank' attribute applicable only to forms?
  • Is there a fix for overriding the save () method and explicitly checks that len ​​(name)! = 0?
  • Did I misunderstand what I once understood resolves my misunderstanding?
+6
django django-models
source share
2 answers

UPDATE: See the model validation documentation in the latest versions of Django.

Original answer : blank = True / False applies only to forms . Data validation currently takes place only at the form level; this will change when the Google Summer of Code work validation model is merged into the trunk.

The only kind of validation that is currently taking place at the model level is any errors that will depend on your database database if it cannot handle what it receives. If CharField is empty, you will usually never get errors from the database, because Django sets the field to an empty string by default.

For now, you should use the save () method for any required model level validation. Soon (if you're on the trunk) or when 1.2 comes out, use the model check material.

+5
source share

From Django Docs :

"Note that empty string values ​​will always be stored as empty strings, not NULL. Use only null = True for non-string fields such as integers, booleans and dates."

Your code stores an empty string.

To illustrate this, try:

 class SimpleTest(TestCase): def test_booking_save(self): b = Booking() b.name = None b.save() 
+1
source share

All Articles