8

在我设置的模型中:

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
4

3 回答 3

8

利用

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=Truefirst 的情况下定义了该字段。现在在代码中更改它不会更改数据库的初始布局。使用South进行数据库迁移或手动更改数据库。

于 2012-12-14T06:48:53.643 回答
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
于 2012-12-14T06:55:12.120 回答
2

也许需要一个默认值

finished = models.IntegerField(default=None,blank=True, null=True)
于 2012-12-14T07:13:44.390 回答