votes up 3

The '%s' attribute has no file associated with it.

Package:
django
github stars 59414
Exception Class:
ValueError

Raise code

    # The standard File contains most of the necessary properties, but
    # FieldFiles can be instantiated without a name, so that needs to
    # be checked for here.

    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()
        if getattr(self, '_file', None) is None:
            self._file = self.storage.open(self.name, 'rb')
        return self._file
😲 Agile task management is now easier than calling a taxi. #Tracklify

Ways to fix

votes up 1 votes down

For example, you have a simple Django model 'Film':

from django.db.models.base import Model
from django.db.models import CharField, ImageField

class Film(Model):
  name = CharField(max_length=255, null=False)
  poster = ImageField()

And you try to show the image field in the django template when it is not set.

<h1>Film info</h4>
<h2>{{ film.poster.url }}</h2>       
<br><img src="{{ film.poster.url }}">
</ul>

To solve this problem, it is enough to add an if statement:

<h1>Film info</h4>
<h2>{{ film.poster.url }}</h2>
<br>
{% if film.poster %}       
<img src="{{ film.poster.url }}">
{% else %}
<img src="url or path to some your default image">
{% endif %}
</ul>

The situation is similar in python code.

film_info = {
  "name": film.name,
  "poster": film.poster.url
}

Solution:

film_info = {
  "name": film.name,
  "poster": film.poster.url if film.poster else "url or path to some your default image"
}

Don't use hasattr(film.poster, 'url'). The error will be the same.

May 18, 2021 rivashchenko answer

Add a possible fix

Please authorize to post fix