My model definition looks like this:
我的模型定义如下:
class MyModel(models.Model):
tag_separator = models.CharField(max_length=1, null=True, blank=True)
The tag_separator
is a single character, and it can be a single space: " "
.
I need to select null=True
in order to get it to work, but when I POST data through my REST API, it saves the tag_separator
as an empty string: "tag_separator": ""
.
tag_separator是单个字符,它可以是单个空格:“”。我需要选择null=True来让它工作,但是当我通过REST API发布数据时,它将tag_separator保存为空字符串:“tag_separator”:“”。
Is there a simple way to stop Django from assuming that my single space string is an empty string?
有什么简单的方法可以阻止Django假设我的单个空间字符串是空字符串吗?
I am using: Django==1.11
and djangorestframework==3.7.7
我使用的是:Django= 1.11, djangorestframework= 3.7.7
2 个解决方案
#1
1
I solved it like this:
我这样解它:
class NonStrippingCharField(models.CharField):
def formfield(self, **kwargs):
kwargs['strip'] = False
return super(NonStrippingCharField, self).formfield(**kwargs)
Then in my model:
然后在我的模型:
class MyModel(models.Model):
tag_separator = NonStrippingCharField(max_length=1, null=True, blank=True)
#2
0
On your Serializer, pass in trim_whitespace=False
into your CharField
. ie:
在序列化器上,将trim_whitespace=False传递到CharField。即:
class MyModelSerializer(serializers.ModelSerializer):
tag_separator = serializers.CharField(trim_whitespace=False)
class Meta:
model = MyModel
Similarly, when you use django's forms, use strip=False
:
同样,在使用django的表单时,使用strip=False:
class MyModelForm(forms.ModelForm):
tag_separator = forms.CharField(strip=False)
class Meta:
model = MyModel
#1
1
I solved it like this:
我这样解它:
class NonStrippingCharField(models.CharField):
def formfield(self, **kwargs):
kwargs['strip'] = False
return super(NonStrippingCharField, self).formfield(**kwargs)
Then in my model:
然后在我的模型:
class MyModel(models.Model):
tag_separator = NonStrippingCharField(max_length=1, null=True, blank=True)
#2
0
On your Serializer, pass in trim_whitespace=False
into your CharField
. ie:
在序列化器上,将trim_whitespace=False传递到CharField。即:
class MyModelSerializer(serializers.ModelSerializer):
tag_separator = serializers.CharField(trim_whitespace=False)
class Meta:
model = MyModel
Similarly, when you use django's forms, use strip=False
:
同样,在使用django的表单时,使用strip=False:
class MyModelForm(forms.ModelForm):
tag_separator = forms.CharField(strip=False)
class Meta:
model = MyModel