Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 500
Hubro Avatar asked Aug 09 '11 09:08

Hubro


People also ask

How do you set a field to null in Django?

null=True will make the field accept NULL values. Blank values for Django field types such as DateTimeField or ForeignKey will be stored as NULL in the database.

How do I make a field optional in Django admin?

By default all fields are required. In order to make a field optional, we have to say so explicitly. If we want to make the pub_time field optional, we add blank=True to the model, which tells Django's field validation that pub_time can be empty.

How do you make a field non mandatory in Django admin?

The simplest way is by using the field option blank=True (docs.djangoproject.com/en/dev/ref/models/fields/#blank).


2 Answers

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) 
like image 77
rewritten Avatar answered Oct 09 '22 04:10

rewritten


This section in the docs makes it sound like you can't set a string-based field to NULL through the admin; it will use the empty string. This is just the way Django does it. It will work for other types of fields.

You'll either have to hack on the admin script or else decide it doesn't really need to be NULL in the database; an empty string is OK.

like image 45
agf Avatar answered Oct 09 '22 04:10

agf