Django:具有空格的模型字段= True,null = True,unique = True在管理员中出现问题 [英] Django: model field having blank=True, null=True, unique=True gives troubles in the admin
问题描述
ipv4_address = models.IPAddressField(verbose_name = _('ipv4 address' ),blank = True,null = True,unique = True,default = None)
ipv6_address = models.GenericIPAddressField(protocol ='IPv6',verbose_name = _('ipv6 address'),blank = True,null = True,unique = True,default = None)
给我这里描述的麻烦: https://code.djangoproject.com/ticket/4136
我如何解决这个问题?
我正在想一个自定义的GenericIPAddressField,将NULL插入到数据库而不是一个空字符串。你怎么看?有其他可能的解决方案吗?
您对自定义字段的建议 GenericIPAddressField
可能是最DRY的解决方案。在上述评论中,akonsu的建议是重写保存方法是一个很好的例子。我使用的一个快速攻击是将您的模型形式的值清除为 None
。
code> class MyModelForm(forms.ModelForm):
class Meta:
model = MyModel
def clean_ipv6_address(self):
返回None而不是空字符串
返回self.cleaned_data.get('ipv6_address')或无
如果您通过django管理员编辑模型,请使用您的模型表单
#!admin.py
class MyModelAdmin(admin.ModelAdmin):
form = MyModelForm
admin.site.register(MyModel,MyModelAdmin)
I have a model in which I have:
ipv4_address = models.IPAddressField(verbose_name=_('ipv4 address'), blank=True, null=True, unique=True, default=None)
ipv6_address = models.GenericIPAddressField(protocol='IPv6', verbose_name=_('ipv6 address'), blank=True, null=True, unique=True, default=None)
And gives me the troubles described here: https://code.djangoproject.com/ticket/4136
How can I solve this?
I was thinking of making a custom GenericIPAddressField which inserts NULL into the database instead of an empty string. What do you think? Are there other possible solutions?
Your suggestion of a custom field GenericIPAddressField
is probably the most DRY solution. akonsu's suggestion in the comments above to override the save method is a good one. A quick hack I have used is to clean the value to None
in your model form.
class MyModelForm(forms.ModelForm):
class Meta:
model = MyModel
def clean_ipv6_address(self):
"""
Return None instead of empty string
"""
return self.cleaned_data.get('ipv6_address') or None
If you edit the model through the django admin, use your model form there
#!admin.py
class MyModelAdmin(admin.ModelAdmin):
form = MyModelForm
admin.site.register(MyModel, MyModelAdmin)
这篇关于Django:具有空格的模型字段= True,null = True,unique = True在管理员中出现问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!