【问题标题】:ValueError: The 'image' attribute has no file associated with it. when testing a model with a NULLABLE image fieldValueError:“图像”属性没有与之关联的文件。使用 NULLABLE 图像字段测试模型时
【发布时间】:2021-01-12 14:30:47
【问题描述】:

我正在测试一个名为 Categorymodel,它看起来像这样:

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 字段是可为空的,但是当我尝试在我的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)

但是没有用。

【问题讨论】:

    标签: python django django-models django-testing


    【解决方案1】:

    你可以这样做,这应该可以工作

    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()
    

    【讨论】:

    • 感谢您的回复,但我已经解决了:)
    【解决方案2】:

    原来这是一个模板错误,因为我没有处理 category 没有图像的可能性,当我在 CategoryListView 上运行测试时,它返回了一个错误,因为 test 类别没有图片

    【讨论】:

      猜你喜欢
      • 2019-02-19
      • 2018-04-28
      • 2023-02-21
      • 2016-02-06
      • 2021-02-11
      • 2020-03-08
      • 2020-08-11
      • 1970-01-01
      • 2021-10-10
      相关资源
      最近更新 更多