ValueError: The 'image' attribute has no file associated with it. when testing a model with a NULLABLE image field
ValueError: The 'image' attribute has no file associated with it. when testing a model with a NULLABLE image field
我正在测试一个名为 Category
的 model
,它看起来像这样:
class Category(models.Model):
image = models.ImageField(upload_to='images', null=True, blank=True)
title = models.CharField(max_length=200, unique=True, blank=False, null=False)
如您所见,image
字段是 nullable 但是当我尝试在我的 TestCase
中创建一个 Category
实例时,我得到了以下错误:
raise ValueError("The '%s' attribute has no file associated with it." % self.field.name)
ValueError: The 'image' attribute has no file associated with it.
这是测试:
def setUp(self):
self.category = Category.objects.create(title='test_category')
我已经试过这样创建它了:
Category.objects.create(title='test_category', image=Null)
但是没有用。
你可以这样做,这应该有效
class Category(models.Model):
image = models.ImageField(upload_to='images/', null=True, blank=True)
title = models.CharField(max_length=200, unique=True, blank=False, null=False)
def setUp(self):
self.category = Category(title='test_category')
self.category.save()
原来这是一个模板错误,因为我没有处理 类别 没有图像的可能性,当我 运行 在 CategoryListView
它返回错误,因为 test 类别没有 image.
我正在测试一个名为 Category
的 model
,它看起来像这样:
class Category(models.Model):
image = models.ImageField(upload_to='images', null=True, blank=True)
title = models.CharField(max_length=200, unique=True, blank=False, null=False)
如您所见,image
字段是 nullable 但是当我尝试在我的 TestCase
中创建一个 Category
实例时,我得到了以下错误:
raise ValueError("The '%s' attribute has no file associated with it." % self.field.name)
ValueError: The 'image' attribute has no file associated with it.
这是测试:
def setUp(self):
self.category = Category.objects.create(title='test_category')
我已经试过这样创建它了:
Category.objects.create(title='test_category', image=Null)
但是没有用。
你可以这样做,这应该有效
class Category(models.Model):
image = models.ImageField(upload_to='images/', null=True, blank=True)
title = models.CharField(max_length=200, unique=True, blank=False, null=False)
def setUp(self):
self.category = Category(title='test_category')
self.category.save()
原来这是一个模板错误,因为我没有处理 类别 没有图像的可能性,当我 运行 在 CategoryListView
它返回错误,因为 test 类别没有 image.