在我设置的模型中:
class Task(models.Model):
EstimateEffort = models.PositiveIntegerField('Estimate hours',max_length=200)
Finished = models.IntegerField('Finished percentage',blank=True)
但是在网页中,如果我没有为该Finished
字段设置值,则会显示错误This field is required
。我试过null=True
了blank=True
。但他们都没有工作。所以你能告诉我如何让一个字段为空。
我发现有一个属性empty_strings_allowed
,我将其设置为 True,但仍然相同,并且我将 models.IntegerField 子类化。它仍然无法工作
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