Django - 如何使 ImageField/FileField 可选? [英] Django - how to make ImageField/FileField optional?
问题描述
class Product(models.Model):
...
image = models.ImageField(upload_to = generate_filename, blank = True)
当我使用 ImageField (blank=True) 并且没有在管理表单中选择图像时,发生异常.
When I use ImageField (blank=True) and do not select image into admin form, exception occures.
在 django 代码中你可以看到:
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 有关于这个问题的工单 #13327,但似乎不能很快修复.如何使这些字段可选?
Django trac has ticket #13327 about this problem, but seems it can't be fixed soon. How to make these field optional?
推荐答案
blank=True
应该可以工作.如果此属性(默认情况下为 False
)设置为 True
,那么它将允许输入空值.
blank=True
should work. If this attribute, which is False
by default, is set to True
then it will allow entry of an empty value.
我的文章应用中有以下类:
I have the following class in my article app:
class Photo(models.Model):
imagename = models.TextField()
articleimage = models.ImageField(upload_to='photos/%Y/%m/%d', blank=True)
我通过使用 ManyToManyField
关系在另一个类中使用上述类:
I make use of the above class in another class by using the ManyToManyField
relationship:
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
在
I want to make images in my articles optional, so blank=True
in
photo = models.ManyToManyField(Photo, related_name='photos', blank=True)
是必要的.如果我愿意,这允许我创建一篇没有任何图像的文章.
is necessary. This allows me to create an article without any images if I want to.
您是否在任何关系中使用 Product
类?如果是这样,请确保在您使用的关系中设置 blank=True
.
Are you using class Product
in any relationship? If so, make sure to set blank=True
in the relationship you are using.
这篇关于Django - 如何使 ImageField/FileField 可选?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!