runnerpaul
runnerpaul

Reputation: 7206

Prevent a ValueError when I don't upload an image in my Django blog post

I have this model:

class News(models.Model):
    title = models.CharField(max_length=255)
    body = models.TextField()
    date = models.DateTimeField(auto_now_add=True)
    author = models.ForeignKey(
        get_user_model(),
        on_delete=models.CASCADE,
    )
    thumb = models.ImageField(blank=True)

    def __str__(self):
        return self.title

    def get_absolute_url(self):
        return reverse('news_detail', args=[str(self.id)])

If I add a blog post and include an image, everything is fine. If I don't include an image and try to view the post in my browser I get this error:

raise ValueError("The '%s' attribute has no file associated with it." % self.field.name)
ValueError: The 'thumb' attribute has no file associated with it.
[01/Apr/2019 08:11:48] "GET /news/ HTTP/1.1" 500 178129

I thought blank=True would prevent any errors if I didn't include an image. I also tried thumb = models.ImageField(blank=True, null=True) based on this question but it made no difference.

How can I have the option of uploading an image or not uploading an image in my blog post without getting an error?

Additional Information

news_detail.html

{% extends 'base.html' %}

{% block content %}
    <div class="news-entry">
        <h2>{{ object.title }}</h2>
            <p>by {{object.author }} | {{ object.date }}</p>
            <p align="center"><img src="{{ object.thumb.url }}" /></p>
            <p>{{ object.body }}</p>
    </div>

    <p><a href="{% url 'news_edit' news.pk %}">Edit</a> |
       <a href="{% url 'news_delete' news.pk %}">Delete</a></p>
    <p>Back to <a href="{% url 'news_list' %}">All News</a>.</p>
{% endblock content %}

Stck trace:

Internal Server Error: /news/2/

Traceback (most recent call last): File "/Users/me/.local/share/virtualenvs/lakelandcc-6nBitmwo/lib/python3.7/site-packages/django/template/base.py", line 829, in _resolve_lookup current = current[bit] TypeError: 'ImageFieldFile' object is not subscriptable

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/Users/me/.local/share/virtualenvs/lakelandcc-6nBitmwo/lib/python3.7/site-packages/django/core/handlers/exception.py", line 34, in inner
    response = get_response(request)
  File "/Users/me/.local/share/virtualenvs/lakelandcc-6nBitmwo/lib/python3.7/site-packages/django/core/handlers/base.py", line 156, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "/Users/me/.local/share/virtualenvs/lakelandcc-6nBitmwo/lib/python3.7/site-packages/django/core/handlers/base.py", line 154, in _get_response
    response = response.render()
  File "/Users/me/.local/share/virtualenvs/lakelandcc-6nBitmwo/lib/python3.7/site-packages/django/template/response.py", line 106, in render
    self.content = self.rendered_content
  File "/Users/me/.local/share/virtualenvs/lakelandcc-6nBitmwo/lib/python3.7/site-packages/django/template/response.py", line 83, in rendered_content
    content = template.render(context, self._request)
  File "/Users/me/.local/share/virtualenvs/lakelandcc-6nBitmwo/lib/python3.7/site-packages/django/template/backends/django.py", line 61, in render
    return self.template.render(context)
  File "/Users/me/.local/share/virtualenvs/lakelandcc-6nBitmwo/lib/python3.7/site-packages/django/template/base.py", line 171, in render
    return self._render(context)
  File "/Users/me/.local/share/virtualenvs/lakelandcc-6nBitmwo/lib/python3.7/site-packages/django/template/base.py", line 163, in _render
    return self.nodelist.render(context)
  File "/Users/me/.local/share/virtualenvs/lakelandcc-6nBitmwo/lib/python3.7/site-packages/django/template/base.py", line 937, in render
    bit = node.render_annotated(context)
  File "/Users/me/.local/share/virtualenvs/lakelandcc-6nBitmwo/lib/python3.7/site-packages/django/template/base.py", line 904, in render_annotated
    return self.render(context)
  File "/Users/me/.local/share/virtualenvs/lakelandcc-6nBitmwo/lib/python3.7/site-packages/django/template/loader_tags.py", line 150, in render
    return compiled_parent._render(context)
  File "/Users/me/.local/share/virtualenvs/lakelandcc-6nBitmwo/lib/python3.7/site-packages/django/template/base.py", line 163, in _render
    return self.nodelist.render(context)
  File "/Users/me/.local/share/virtualenvs/lakelandcc-6nBitmwo/lib/python3.7/site-packages/django/template/base.py", line 937, in render
    bit = node.render_annotated(context)
  File "/Users/me/.local/share/virtualenvs/lakelandcc-6nBitmwo/lib/python3.7/site-packages/django/template/base.py", line 904, in render_annotated
    return self.render(context)
  File "/Users/me/.local/share/virtualenvs/lakelandcc-6nBitmwo/lib/python3.7/site-packages/django/template/loader_tags.py", line 62, in render
    result = block.nodelist.render(context)
  File "/Users/me/.local/share/virtualenvs/lakelandcc-6nBitmwo/lib/python3.7/site-packages/django/template/base.py", line 937, in render
    bit = node.render_annotated(context)
  File "/Users/me/.local/share/virtualenvs/lakelandcc-6nBitmwo/lib/python3.7/site-packages/django/template/base.py", line 904, in render_annotated
    return self.render(context)
  File "/Users/me/.local/share/virtualenvs/lakelandcc-6nBitmwo/lib/python3.7/site-packages/django/template/base.py", line 987, in render
    output = self.filter_expression.resolve(context)
  File "/Users/me/.local/share/virtualenvs/lakelandcc-6nBitmwo/lib/python3.7/site-packages/django/template/base.py", line 671, in resolve
    obj = self.var.resolve(context)
  File "/Users/me/.local/share/virtualenvs/lakelandcc-6nBitmwo/lib/python3.7/site-packages/django/template/base.py", line 796, in resolve
    value = self._resolve_lookup(context)
  File "/Users/me/.local/share/virtualenvs/lakelandcc-6nBitmwo/lib/python3.7/site-packages/django/template/base.py", line 837, in _resolve_lookup
    current = getattr(current, bit)
  File "/Users/me/.local/share/virtualenvs/lakelandcc-6nBitmwo/lib/python3.7/site-packages/django/db/models/fields/files.py", line 61, in url
    self._require_file()
  File "/Users/me/.local/share/virtualenvs/lakelandcc-6nBitmwo/lib/python3.7/site-packages/django/db/models/fields/files.py", line 38, in _require_file
    raise ValueError("The '%s' attribute has no file associated with it." % self.field.name)
ValueError: The 'thumb' attribute has no file associated with it.
[01/Apr/2019 08:29:46] "GET /news/2/ HTTP/1.1" 500 160702

Upvotes: 1

Views: 1040

Answers (2)

Chintan Bhatt
Chintan Bhatt

Reputation: 181

Add a condition in template file to check if the thumb image exists. Show the image only if it exists otherwise don't. Change the code:

<p align="center"><img src="{{ object.thumb.url }}" /></p>

to:

{% if object.thumb %}
    <p align="center"><img src="{{ object.thumb.url }}" /></p>
{% endif %}

Upvotes: 2

Jibin Mathews
Jibin Mathews

Reputation: 1135

please check if the image exists before calling url

 <p align="center"><img src="{{ object.thumb.url }}" /></p>

to

{% if object.thumb %}
 <p align="center"><img src="{{ object.thumb.url }}" /></p>
{% endif %}

Upvotes: 5

Related Questions