这个字段在django中是必需的错误

时间:2012-12-14 06:40:46

标签: python django

在我设定的模型中:

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=Trueblank=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

3 个答案:

答案 0 :(得分:4)

在表单上,​​您可以在字段上设置required=False

Finished = forms.IntegerField(required=False)

或者为了避免在ModelForm上重新定义字段,

def __init__(self, *args, **kwargs):
    super(MyForm, self).__init__(*args, **kwargs)
    self.fields['Finished'].required = False
    #self.fields['Finished'].empty_label = 'Nothing' #optionally change the name

答案 1 :(得分:2)

使用

Finished = models.IntegerField('Finished percentage', blank=True, null=True)

阅读https://docs.djangoproject.com/en/1.4/ref/models/fields/#blank

null is purely database-related, whereas blank is validation-related.

您可能先定义了没有null=True的字段。现在在代码中更改它不会更改数据库的初始布局。使用South进行数据库迁移或手动更改数据库。

答案 2 :(得分:2)

可能需要默认值

finished = models.IntegerField(default=None,blank=True, null=True)