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

jim*_*wan 5 python django

在我设置的模型中:

class Task(models.Model):
    EstimateEffort = models.PositiveIntegerField('Estimate hours',max_length=200)
    Finished = models.IntegerField('Finished percentage',blank=True)
Run Code Online (Sandbox Code Playgroud)

但是在网页中,如果我没有为该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
Run Code Online (Sandbox Code Playgroud)

Cha*_*arl 6

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

Finished = forms.IntegerField(required=False)
Run Code Online (Sandbox Code Playgroud)

或者为了避免重新定义 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
Run Code Online (Sandbox Code Playgroud)


Mat*_*ias 5

使用

Finished = models.IntegerField('Finished percentage', blank=True, null=True)
Run Code Online (Sandbox Code Playgroud)

阅读https://docs.djangoproject.com/zh-CN/1.4/ref/models/fields/#blank

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

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