How can I allow django admin to set a field to NULL?

Hubro picture Hubro · Aug 9, 2011 · Viewed 20.7k times · Source

I've set my Model field to null=True, which allows NULL in MySQL, but I can't seem to assign NULL to the field through Django Admin. I've tried also setting blank=True, but that just sets the field to an empty string. Following this didn't work either, as the field value was set to "None", the string.

Any ideas?

Answer

rewritten picture rewritten · Aug 9, 2011

Try to overwrite the save() method of the model, to check for empty values:

class MyModel(models.Model):

    my_nullable_string = models.CharField(max_length=15, null=True, blank=True)

    def save(self, *args, **kwargs):
         if not self.my_nullable_string:
              self.my_nullable_string = None
         super(MyModel, self).save(*args, **kwargs)