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

PythonMysqlSqlDjangoDjango Admin

Python Problem Overview


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?

Python Solutions


Solution 1 - Python

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)

Solution 2 - Python

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.

Solution 3 - Python

try this code, here Language.subregion hass null=True this code overwrites admin form settings (LanguageAdmin) and sets "subregion" field property - required to False

from app.models import Language
from django.contrib import admin

class Language(models.Model):
    subregion = models.ForeignKey(SubRegion, null=True)
    code = models.CharField(max_length=10, unique=True)

class LanguageAdmin(admin.ModelAdmin):

    def get_form(self, request, obj=None, **kwargs):
        form = super(LanguageAdmin, self).get_form(request, obj, **kwargs)
        form.base_fields['subregion'].required = False
        return form

admin.site.register(Language, LanguageAdmin)

Solution 4 - Python

Usually, when you pass both null=True and blank=True, if you leave the field blank in the admin, Django will use NULL for its value.

EDIT:

as agf explains in his answer, this is true for all types except CharField and TextField.

Solution 5 - Python

I often use Django just for the Admin and need to preserve a lot of NULLs in the db. I use this snippet to set all empty strings on a particular object to NULL.

def save(self, *args, **kwargs):
    for var in vars(self):
        if not var.startswith('_'):
            if self.__dict__[var] == '':
                self.__dict__[var] = None
    super(MyModel, self).save(*args, **kwargs)

Solution 6 - Python

Note that this is fixed in Django 2.0.1 -- from that version on, empty values will be saved as None for nullable Charfields.

Ticket: https://code.djangoproject.com/ticket/4136

Commit: https://github.com/django/django/commit/267dc4adddd2882182f71a7f285a06b1d4b15af0

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionHubroView Question on Stackoverflow
Solution 1 - PythonrewrittenView Answer on Stackoverflow
Solution 2 - PythonagfView Answer on Stackoverflow
Solution 3 - PythonpymenView Answer on Stackoverflow
Solution 4 - PythonmdeousView Answer on Stackoverflow
Solution 5 - PythonMark PhillipView Answer on Stackoverflow
Solution 6 - PythonSymmetricView Answer on Stackoverflow