如何允许django admin将字段设置为NULL?

时间:2022-12-26 07:21:54

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.

我已经将模型字段设置为null=True,这在MySQL中允许使用null,但是我似乎不能通过Django Admin为字段分配null。我也尝试过设置blank=True,但这只是将字段设置为空字符串。当字段值被设置为“None”时,这个字符串也不起作用。

Any ideas?

什么好主意吗?

6 个解决方案

#1


23  

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

尝试覆盖模型的save()方法,检查空值:

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)

#2


13  

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.

文档中的这个部分使它听起来像您不能通过admin设置一个基于字符串的字段为空;它将使用空字符串。Django就是这么做的。它将适用于其他类型的字段。

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.

您要么必须修改管理脚本,要么决定它在数据库中不需要为NULL;空字符串是可以的。

#3


5  

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.

通常,当您同时传递null=True和blank=True时,如果在admin中保留字段为空,Django将为其值使用null。

EDIT:

编辑:

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

正如agf在他的回答中解释的那样,除了CharField和TextField之外,所有类型都是如此。

#4


3  

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.

我经常只对管理员使用Django,并且需要在db中保存大量的null。我使用这段代码将特定对象上的所有空字符串设置为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)

#5


3  

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

试试这段代码,这里是语言。子区域hass null=True这段代码重写了admin表单设置(LanguageAdmin),并设置了“subregion”字段属性——必须为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)

#6


1  

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

注意,这在Django 2.0.1中得到了修正——从那个版本开始,空值将被保存为None,用于可空的Charfields。

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

门票:https://code.djangoproject.com/ticket/4136

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

提交:https://github.com/django/django/commit/267dc4adddd2882182f71a7f285a06b1d4b15af0

#1


23  

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

尝试覆盖模型的save()方法,检查空值:

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)

#2


13  

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.

文档中的这个部分使它听起来像您不能通过admin设置一个基于字符串的字段为空;它将使用空字符串。Django就是这么做的。它将适用于其他类型的字段。

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.

您要么必须修改管理脚本,要么决定它在数据库中不需要为NULL;空字符串是可以的。

#3


5  

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.

通常,当您同时传递null=True和blank=True时,如果在admin中保留字段为空,Django将为其值使用null。

EDIT:

编辑:

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

正如agf在他的回答中解释的那样,除了CharField和TextField之外,所有类型都是如此。

#4


3  

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.

我经常只对管理员使用Django,并且需要在db中保存大量的null。我使用这段代码将特定对象上的所有空字符串设置为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)

#5


3  

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

试试这段代码,这里是语言。子区域hass null=True这段代码重写了admin表单设置(LanguageAdmin),并设置了“subregion”字段属性——必须为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)

#6


1  

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

注意,这在Django 2.0.1中得到了修正——从那个版本开始,空值将被保存为None,用于可空的Charfields。

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

门票:https://code.djangoproject.com/ticket/4136

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

提交:https://github.com/django/django/commit/267dc4adddd2882182f71a7f285a06b1d4b15af0