58

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?

Community
  • 1
  • 1
Hubro
  • 56,214
  • 69
  • 228
  • 381

6 Answers6

48

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)
phoenix
  • 7,988
  • 6
  • 39
  • 45
rewritten
  • 16,280
  • 2
  • 47
  • 50
20

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.

agf
  • 171,228
  • 44
  • 289
  • 238
  • 7
    +1 If the field you are dealing with is set to be `unique`, then the only option is "hacking the admin" – Caumons Sep 02 '13 at 11:53
  • 1
    I'm using null in a ForeignKey, and it still doesn't allow it to be null. So it's not a string-related issue. – Anoyz Jan 20 '16 at 16:35
  • 1
    I'm coming to this late but this is crazy!! When you have `unique=True` and `blank=True` this glaring problem with the Django admin will slip through Test Client and model unit tests, rearing it's head only when someone tries to leave out a unique field more than once. IMO this is basically a bug seeing as in every case _except_ the admin, `null=True` + no default value means a NULL value in the DB. – toxefa Jan 12 '17 at 20:16
12

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)
pymen
  • 5,737
  • 44
  • 35
  • That fixes the issue for the record level CRUD form, but not for the multirow or table level form... Any idea on how to fix that also? Thx – Daniel Lema Dec 01 '21 at 23:09
  • @DanielLema you may try to override def get_changelist_form or whatever method is used by Django to show the form – pymen Dec 02 '21 at 07:58
11

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.

mdeous
  • 17,513
  • 7
  • 56
  • 60
5

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)
Mark Phillip
  • 1,453
  • 17
  • 22
3

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

Symmetric
  • 4,495
  • 5
  • 32
  • 50
  • 1
    Seems to me (based on the code in that commit and some testing) that this will only affect DB connections that have `interprets_empty_strings_as_nulls` set to True, so not exactly fixed for all CharFields and not fixed for the OP's use case with MySQL either. – Matt Dodge Apr 13 '20 at 20:33