【问题标题】:Django - how to make ImageField/FileField optional?Django - 如何使 ImageField/FileField 可选?
【发布时间】:2011-02-10 06:45:57
【问题描述】:
class Product(models.Model):
    ...    
    image = models.ImageField(upload_to = generate_filename, blank = True)  

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

在 django 代码中你可以看到:

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 有关于这个问题的票 #13327,但似乎不能很快解决。如何使这些字段可选?

【问题讨论】:

  • 你找到解决办法了吗,看来我现在也有同样的问题

标签: django django-models


【解决方案1】:

blank=True 应该可以工作。如果此属性(默认为False)设置为True,则允许输入空值。

我的文章应用中有以下类:

class Photo(models.Model):
        imagename = models.TextField()
        articleimage = models.ImageField(upload_to='photos/%Y/%m/%d', blank=True)

我通过ManyToManyField关系在另一个类中使用上述类:

class Article(models.Model):
        pub_date = models.DateTimeField(default=timezone.now)
        slug = models.SlugField(max_length=130)
        title = models.TextField()
        photo = models.ManyToManyField(
            Photo, related_name='photos', blank=True)
        author = models.ForeignKey(User)
        body = models.TextField()
        categories = models.ManyToManyField(
            Category, related_name='articles', null=True)

我想让我的文章中的图片是可选的,所以blank=True in

photo = models.ManyToManyField(Photo, related_name='photos', blank=True)

是必要的。如果我愿意,这允许我创建没有任何图像的文章。

您是否在任何关系中使用Product 类?如果是这样,请确保在您使用的关系中设置blank=True

【讨论】:

  • 你为什么不使用 null 作为图像?
  • 尝试这样做,我得到django.db.utils.IntegrityError: NOT NULL constraint failed: new__app_idea.image
【解决方案2】:

设置null=True(见documentation

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

【讨论】:

  • null=True 很吓人,blank=True 就足够了,因为 ImageField/FileField 实际上是 CharFields 下面...
  • null=True 对 FileField 或 ImageField 没有任何作用 code.djangoproject.com/ticket/10244
【解决方案3】:

如果 'optional' 表示您希望能够完全忽略图像字段。然后blank=True,就这样吧。但是,如果您仍然遇到相同的错误,那么这意味着您在某处的模板中使用它的url,或者您试图在models.pyviews.py 中打开图像的路径(可能是调整图像大小或其他一些后端预处理)。 这就是为什么总是建议在处理文件时使用try - catch 块。

【讨论】:

    猜你喜欢
    • 2012-05-08
    • 1970-01-01
    • 2013-04-19
    • 1970-01-01
    • 2023-03-19
    • 1970-01-01
    • 2011-08-21
    相关资源
    最近更新 更多