pythonmysqlsqldjangodjango-admin

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


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?


Solution

  • 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)