【问题标题】:can't upload image from database in django server无法从 django 服务器中的数据库上传图像
【发布时间】:2021-10-30 00:55:20
【问题描述】:

在我的项目中,我试图将图像保存在数据库中,接下来我想从数据库中获取该图像 在我的仪表板中,一切运行良好,imgs 保存在 db 中,但是当我尝试从 db 获取 url 并将其分配给 img src="" chrome 时说 404(未找到)

这是我的模特

class Id(models.Model):
    first_name = models.CharField(max_length=100, null=True)
    image = models.ImageField(default='defaut.jpg', upload_to='document_pics')

    def __str__(self):
        return self.first_nam

img savinig 在documents_pics 文件夹中然后我尝试在views.py 中从db 中获取数据并将其发送到home.html

def home(request):
    context = {
        'posts': Id.objects.all(),
        'title': 'Home'
    }
    
    return render(request, 'blog/home.html', context)

home.html

{% extends 'blog/base.html' %}

{% block content %}

    {% for post in posts %}
        <article class="media content-section">
            <img src="{{ post.image }}  " width="200" height="200"
        </article>
    {% endfor %}
{% endblock content %}

然后我收到 404 错误

【问题讨论】:

  • 设置中的MEDIA_URL和MEDIA值是多少?

标签: django django-forms django-templates http-status-code-404 django-imagekit


【解决方案1】:

在您的 html 模板中的图像 jinja 代码上尝试这些路径

{% 扩展 'blog/base.html' %}

{% 块内容 %}

{% for post in posts %}
    <article class="media content-section">
        <img src="{{ post.image.url }}  " width="200" height="200"
    </article>
{% endfor %}

{% 结束块内容 %

【讨论】:

  • 好的,但你能解释一下发生了什么。 .url 是什么意思:dd
  • 请添加更多详细信息以扩展您的答案,例如工作代码或文档引用。
猜你喜欢
  • 2011-10-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-02-06
  • 2016-11-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多