【问题标题】:Display images in Django在 Django 中显示图像
【发布时间】:2015-06-04 07:20:22
【问题描述】:

我有一个 django 应用程序,它允许用户使用它提交图像。现在我的模型看起来像

class Posting(models.Model):
    title = models.CharField(max_length=150)
    images = models.ForeignKey(Image, null=True)

class Image(models.Model):
    img = models.ImageField(upload_to="photos/",null=True, blank=True)

我正在尝试在我的模板中显示图像,但我似乎无法让它工作。我经历了无数的堆栈溢出帖子,但没有任何运气。在我的模板中,我有

{ for post in postings }
    <img src"{{ post.image.url }} #and many variations of this

但是其他似乎显示了 url。网址似乎总是空白。任何帮助将不胜感激!

【问题讨论】:

  • 试试这个 - 因为您的 Posting 模型具有 Image 模型的 'images' 命名属性。
  • &lt;img src="/{{post.images.img}}"/&gt; 试试这个。我想问题出在相对路径上。将“/”附加到路径。

标签: django image imagefield


【解决方案1】:

这就是我的工作方式。

settings.py

import os
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
STATIC_URL = '/static/'

STATICFILES_DIRS = (
    os.path.join(BASE_DIR, "static"),
)

MEDIA_ROOT = (
BASE_DIR
)


MEDIA_URL = '/media/'

models.py ...

image = models.ImageField(upload_to='img')

urls.py(项目的)

if settings.DEBUG:
urlpatterns = urlpatterns + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

模板 (.html)

<img src="{{ post.image.url }}" alt="img">

【讨论】:

  • 你的 urls.py 中的 static 是什么?
【解决方案2】:

做这样的事情。此代码在我的应用程序中运行。

views.py:

def list(request):
  images = Image.objects.all()
  return render(request, "list.html", {'images': images})

list.html:

{% for i in images %}
    <img src="{{ i.image.url }}" width="500px"/>
{% endfor %}

【讨论】:

    【解决方案3】:

    模板标签应该是:

    <img src="{{ post.images.img.url }}" ... >
    

    【讨论】:

      【解决方案4】:

      你应该期待类似于:

      {% for post in postings %}
        <img src="{{ post.image.url }}">
      {% endfor %}
      

      这里有几个注意事项 --

      • 图像以文件的形式提供,任何为您的应用程序(runserver、nginx、apache 等)提供服务的东西都需要能够路由该文件。
      • 您必须确保您正在构建上下文以供模板引擎使用。对于在上下文中找不到的值,它将静默失败。

      【讨论】:

      • 谢谢,我试过了,但没有成功。如果每个帖子都有foreignKey,这仍然有效吗?这是一对多正确吗?
      【解决方案5】:

      您似乎正在尝试学习 Corey Schaefer 的视频教程系列。如果是这样,我的建议将无济于事,但如果没有,Corey Schaefer 有一个视频,其中涵盖了您正在尝试做的事情 https://youtu.be/FdVuKt_iuSI?list=PL-osiE80TeTtoQCKZ03TU5fNfx2UY6U4p

      您必须设置相当多的设置并覆盖一些默认值。 django 文档有两种方法,一种用于在 localhost 上进行开发,另一种用于生产:https://docs.djangoproject.com/en/2.2/howto/static-files/

      【讨论】:

        猜你喜欢
        • 2015-04-15
        • 1970-01-01
        • 2011-03-17
        • 1970-01-01
        • 2020-08-16
        • 2013-02-16
        • 2020-10-17
        • 1970-01-01
        相关资源
        最近更新 更多