The '%s' attribute has no file associated with it.
Package:
django
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
Links to the raise (1)
https://github.com/django/django/blob/7cca22964c09e8dafc313a400c428242404d527a/django/db/models/fields/files.py#L40Ways to fix
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.
Add a possible fix
Please authorize to post fix