当我没有在我的 Django 博客文章中上传图像时防止出现 ValueError

Posted

技术标签:

【中文标题】当我没有在我的 Django 博客文章中上传图像时防止出现 ValueError【英文标题】:Prevent a ValueError when I don't upload an image in my Django blog post 【发布时间】:2019-08-22 07:23:27 【问题描述】:

我有这个模型:

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

如果我添加博客文章并包含图片,一切都很好。如果我不包含图片并尝试在浏览器中查看帖子,则会收到此错误:

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

我认为blank=True 如果不包含图像,会防止出现任何错误。我还根据this 问题尝试了thumb = models.ImageField(blank=True, null=True),但没有任何区别。

如何在我的博客文章中选择上传图片或不上传图片而不会出错?

其他信息

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 跟踪:

Internal Server Error: /news/2/

Traceback(最近一次调用最后一次): _resolve_lookup 中的文件“/Users/me/.local/share/virtualenvs/lakelandcc-6nBitmwo/lib/python3.7/site-packages/django/template/base.py”,第 829 行 当前 = 当前[位] TypeError: 'ImageFieldFile' 对象不可下标

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

【问题讨论】:

喜欢这个? thumb = models.ImageField(blank=True, null=True)。我试过了,但没有任何区别。 @runnerpaul 你从哪里得到这个错误?在管理站点或其他视图中?如果是其他视图,请添加视图和模板的代码。 不需要对图像字段使用 null = True 可以发布完整的堆栈跟踪 也许,object.thumb.url if object.thumb else "notfoundimage.jpg"? 【参考方案1】:

调用url前请检查图片是否存在

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

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

【讨论】:

【参考方案2】:

在模板文件中添加条件以检查缩略图是否存在。仅在图像存在时才显示图像,否则不显示。修改代码:

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

到:

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

【讨论】:

以上是关于当我没有在我的 Django 博客文章中上传图像时防止出现 ValueError的主要内容,如果未能解决你的问题,请参考以下文章

在 django 博客站点中集成文本编辑器

如何在 django 中将多张图片上传到博客文章

无法从 django 服务器中的数据库上传图像

Django Ckeditor图像浏览器找不到图像

使用ajax在codeigniter中上传图片

如何在 CKEditor 5 中启用图像上传支持?