Django - 如何使ImageField / FileField可选? [英] Django - how to make ImageField/FileField optional?

查看:170
本文介绍了Django - 如何使ImageField / FileField可选?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

pre $ class Product(models.Model):
...
image = models.ImageField(upload_to = generate_filename,blank = True)

当我使用ImageField(blank = True)并且不要将图像选择为管理表单时,异常发生。



在django代码中,您可以看到这样:

 类FieldFile(File):
....

def _require_file(self):
如果不是self:
raise ValueError('%s'属性没有与之关联的文件。 %self.field.name)

def _get_file(self):
self._require_file()
...

Django trac有关于这个问题的票证#13327,但似乎不能很快修复。如何使这些字段可选?

解决方案

设置 null = True 请参阅文档

  class Product(models.Model):
...
image = models.ImageField(upload_to = generate_filename,blank = True,null =真的)


class Product(models.Model):
    ...    
    image = models.ImageField(upload_to = generate_filename, blank = True)  

When I use ImageField (blank=True) and do not select image into admin form, exception occures.

In django code you can see this:

class FieldFile(File):
   ....

    def _require_file(self):
        if not self:
            raise ValueError("The '%s' attribute has no file associated with it." % self.field.name)

    def _get_file(self):
        self._require_file()
        ...

Django trac has ticket #13327 about this problem, but seems it can't be fixed soon. How to make these field optional?

解决方案

Set null=True (see documentation)

class Product(models.Model):
    ...    
    image = models.ImageField(upload_to=generate_filename, blank=True, null=True)

这篇关于Django - 如何使ImageField / FileField可选?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆