mirror of
https://github.com/django/django.git
synced 2025-10-24 06:06:09 +00:00
Fixed #4136 -- Made ModelForm save empty values for nullable CharFields as NULL.
Previously, empty values were saved as strings.
This commit is contained in:
@@ -13,8 +13,8 @@ from django.core.exceptions import (
|
||||
ObjectDoesNotExist, ValidationError,
|
||||
)
|
||||
from django.db import (
|
||||
DEFAULT_DB_ALIAS, DJANGO_VERSION_PICKLE_KEY, DatabaseError, connections,
|
||||
router, transaction,
|
||||
DEFAULT_DB_ALIAS, DJANGO_VERSION_PICKLE_KEY, DatabaseError, connection,
|
||||
connections, router, transaction,
|
||||
)
|
||||
from django.db.models import signals
|
||||
from django.db.models.constants import LOOKUP_SEP
|
||||
@@ -1087,7 +1087,9 @@ class Model(six.with_metaclass(ModelBase)):
|
||||
for field_name in unique_check:
|
||||
f = self._meta.get_field(field_name)
|
||||
lookup_value = getattr(self, f.attname)
|
||||
if lookup_value is None:
|
||||
# TODO: Handle multiple backends with different feature flags.
|
||||
if (lookup_value is None or
|
||||
(lookup_value == '' and connection.features.interprets_empty_strings_as_nulls)):
|
||||
# no value, skip the lookup
|
||||
continue
|
||||
if f.primary_key and not self._state.adding:
|
||||
|
||||
@@ -1086,6 +1086,9 @@ class CharField(Field):
|
||||
# will be validated twice. This is considered acceptable since we want
|
||||
# the value in the form field (to pass into widget for example).
|
||||
defaults = {'max_length': self.max_length}
|
||||
# TODO: Handle multiple backends with different feature flags.
|
||||
if self.null and not connection.features.interprets_empty_strings_as_nulls:
|
||||
defaults['empty_value'] = None
|
||||
defaults.update(kwargs)
|
||||
return super(CharField, self).formfield(**defaults)
|
||||
|
||||
|
||||
@@ -214,10 +214,11 @@ class Field(object):
|
||||
|
||||
|
||||
class CharField(Field):
|
||||
def __init__(self, max_length=None, min_length=None, strip=True, *args, **kwargs):
|
||||
def __init__(self, max_length=None, min_length=None, strip=True, empty_value='', *args, **kwargs):
|
||||
self.max_length = max_length
|
||||
self.min_length = min_length
|
||||
self.strip = strip
|
||||
self.empty_value = empty_value
|
||||
super(CharField, self).__init__(*args, **kwargs)
|
||||
if min_length is not None:
|
||||
self.validators.append(validators.MinLengthValidator(int(min_length)))
|
||||
@@ -227,7 +228,7 @@ class CharField(Field):
|
||||
def to_python(self, value):
|
||||
"Returns a Unicode object."
|
||||
if value in self.empty_values:
|
||||
return ''
|
||||
return self.empty_value
|
||||
value = force_text(value)
|
||||
if self.strip:
|
||||
value = value.strip()
|
||||
|
||||
Reference in New Issue
Block a user