【问题标题】:This field is required error in django此字段是必需的 Django 中的错误
【发布时间】:2012-12-02 04:08:38
【问题描述】:

在我设置的模型中:

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

【问题讨论】:

  • 你的表单是什么样子的??
  • 你做了“python manage.py syncdb”吗?
  • @Yuji Tomita 我使用管理员的默认表单,而不是我的自定义表单

标签: python django


【解决方案1】:

使用

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进行数据库迁移或手动更改数据库。

【讨论】:

  • 对不起,这不起作用,即使我设置了空白=真,空=真。它需要输入一个值
  • 我把数据库文件中的表删除了,再运行sycndb,还是一样
【解决方案2】:

在表单上,​​您可以在字段上设置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

【讨论】:

  • 模型可以是:Finished = models.IntegerField(blank=True, null=True)
  • 您已经有表格了吗?因为当您在表单上指定字段时,默认情况下这些字段是必需的,那么您在模型中将其设为可空并不重要,因为它在 html 中表示时是必需的。但是您不能将表单字段设为可选,而模型上的字段则为必填
【解决方案3】:

可能需要一个默认值

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

【讨论】:

    猜你喜欢
    • 2020-06-02
    • 2019-04-13
    • 2016-04-29
    • 2021-04-10
    • 2019-06-11
    • 1970-01-01
    • 2011-08-13
    • 1970-01-01
    相关资源
    最近更新 更多