Home > Back-end >  ValueError: The 'main_image' attribute has no file associated with it. on Django tests
ValueError: The 'main_image' attribute has no file associated with it. on Django tests

Time:08-22

I'm doing a test and I don't understand why this error is raised

The test:

def test_show_one_blog(self):
    blog0 = Blog.objects.create(name="American persuit", content="I don't know") 
    url = self.client.get(reverse(viewname="blogs:blog_view", kwargs={"pk": 1}))

    self.assertEqual(url.status_code, 200)
    self.assertContains(url, text="American persuit")
    self.assertContains(url, "I don't know")
    self.assertContains(url, '2022-8-20')

The model:

class Blog(models.Model):
    name = models.CharField(max_length=140, blank=False, null=False)
    content = models.TextField(max_length=700, blank=False, null=False)
    pub_date = models.DateField(default=timezone.now(), blank=False, null=False)
    main_image = models.ImageField(null=True, blank=True)

    def __str__(self) -> str:
        return self.name

the error:

the error

CodePudding user response:

Yes, main image does not have a file associated, this is because you are not assigning one. If there is no file, it will raise a ValueError in the template. The way I solve this is adding a method to the model like so:

class Blog(models.Model):
    ...

    def get_image(self):
        try:
            return self.main_image.attribute #(replace attribute with file, path, or url)
        except ValueError:
            return None # Alternatively, you can return a default image here.
        

And then using that method in the template instead. (Or anywhere else it's needed)

  • Related