django中此字段为必填错误 [英] This field is required error in django
问题描述
在我设置的模型中:
class Task(models.Model):
EstimateEffort = models.PositiveIntegerField('Estimate hours',max_length=200)
Finished = models.IntegerField('Finished percentage',blank=True)
但是在网页中,如果我没有为 Finished
字段设置值,则会显示错误此字段为必填项
。我尝试了 null = True
和 blank = True
。但是他们都不起作用。所以,请您告诉我如何使字段允许为空。
But in the web page, if I didn't set a value for the Finished
field, it is showing an error This field is required
. I tried null=True
and blank=True
. But none of them worked. So could you please tell me how can I make a field allowed to be empty.
我发现有一个属性 empty_strings_allowed
,我将其设置为True,但仍保持不变,并且将models.IntegerField子类化。仍然无法正常工作
I have found that there is a attribute empty_strings_allowed
, i set it to True, but still the same, and i subclass the models.IntegerField. It still can not work
class IntegerNullField(models.IntegerField):
description = "Stores NULL but returns empty string"
empty_strings_allowed =True
log.getlog().debug("asas")
def to_python(self, value):
log.getlog().debug("asas")
# this may be the value right out of the db, or an instance
if isinstance(value, models.IntegerField):
# if an instance, return the instance
return value
if value == None:
# if db has NULL (==None in Python), return empty string
return ""
try:
return int(value)
except (TypeError, ValueError):
msg = self.error_messages['invalid'] % str(value)
raise exceptions.ValidationError(msg)
def get_prep_value(self, value):
# catches value right before sending to db
if value == "":
# if Django tries to save an empty string, send to db None (NULL)
return None
else:
return int(value) # otherwise, just pass the value
推荐答案
使用
Finished = models.IntegerField('Finished percentage', blank=True, null=True)
阅读 https ://docs.djangoproject.com/zh-CN/1.4/ref/models/fields/#blank :
null纯粹是空的与数据库相关,而空白与验证相关。
您可能已经定义了没有 null = True <的字段/ code>首先。现在,更改代码中的内容将不会更改数据库的初始布局。使用南进行数据库迁移或手动更改数据库。
You might have defined the field without null=True
first. Changing that in the code now won't change the initial layout of the database. Use South for database migrations or change the database manually.
这篇关于django中此字段为必填错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!