【问题标题】:Django not getting images that are uploaded to sqliteDjango 没有获取上传到 sqlite 的图像
【发布时间】:2016-03-05 08:27:59
【问题描述】:

图像没有进入模板。

settings.py

​​>
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')

html

{% for question in question_list %}
<img src= "{{question.image}}">

models.py

​​>
class NewQuestion(models.Model):
    category = models.ForeignKey(Category)
    question_text = models.CharField(max_length = 200, unique = True, null =        False)
    image = models.ImageField(upload_to='images')

    def __unicode__(self):
        return self.question_text

【问题讨论】:

  • 如果我在 html 上输入 {{question.image}},我会得到 images/frame.jpg
  • 试试{{question.image.url}}

标签: html django imagefield display


【解决方案1】:

要使用 Django 的模板语言从 ImageField 渲染照片,需要以下语法:

{{ image.url }}

在你的情况下:

{% for question in question_list %}
    <img src= "{{ question.image.url }}">
{% endfor %}

【讨论】:

    【解决方案2】:

    试试这个:

    {% for question in question_list %}
       <img src= "{{question.image.url}}">
    {% endfor %}
    

    参考docs

    一个只读属性,通过调用底层存储类的 url() 方法来访问文件的相对 URL。

    更新:

    将此添加到您的 urls.py

    from django.conf import settings
    from django.conf.urls.static import static
    
    urlpatterns = [
        # ... the rest of your URLconf goes here ...
    ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
    

    【讨论】:

    • 我也保留了 {%endfor%} 但我没有得到图像。
    • 我想知道图片的具体存储位置,目前我的图片会自动存储在 media/images 中
    • 图像直接存储在“媒体/图像”中,因为您将MEDIA_ROOT 指定为mediaupload_to 指定为images
    • 不是{{questions.image.url}},而是{{question.image.url}}
    • 我只写了 {{question.image.url}}
    猜你喜欢
    • 1970-01-01
    • 2015-01-05
    • 2020-05-07
    • 2021-08-12
    • 1970-01-01
    • 2011-11-06
    • 2020-09-16
    • 2018-03-12
    • 2015-04-27
    相关资源
    最近更新 更多