【问题标题】:Images from ImageField in Django don't load in template来自 Django 中 ImageField 的图像不会加载到模板中
【发布时间】:2013-04-18 06:38:03
【问题描述】:

我正在本地机器上使用 Django(1.5.1) 构建画廊。在我的专辑模型中,我有一个 ImageField。有一个视图可以显示相册的所有图像。它运作良好,但最后图像不显示。如您所见,图像有边框,但无法加载图像。

截图

models.py

class Category(models.Model):
 ###  
class Album(models.Model):   
    category = models.ForeignKey(Category, related_name='albums')
 ###
class Image(models.Model):
    album = models.ForeignKey(Album)
    image = models.ImageField(upload_to = 'images/albums/')

views.py

def detail(request, album_id):
    album = get_object_or_404(Album, pk=album_id)
    return render(request, 'gallery/detail.html', {'album': album})

detail.html

<h1>{{ album.title }}</h1>
{% for image in album.image_set.all %}
  <a>  <img src="{{ image.image.url }}" height="420"></a>
{% endfor %}

如果这是我的相册地址:http://localhost:8000/gallery/1/

那么图片网址为:http://localhost:8000/media/images/albums/photo_4.JPG (I get 404 when enter it in browser)

此媒体根目录和网址:

MEDIA_ROOT = '/media/'    
MEDIA_URL = '/localhost:8000/media/'  

我的媒体根有 777 权限

我现在该怎么办?问题出在哪里?

【问题讨论】:

  • 似乎服务器在请求图像时返回了 Not Found 响应。您可以在浏览器中检查图像元素并发布图像src 属性中的地址是什么?
  • 用有关 url 和 root 设置的更多信息编辑了我的问题。
  • 这很奇怪,应该是/media/images/albums/photo_4.jpg。尝试手动在浏览器中输入此地址http://localhost:8000/media/images/albums/photo_4.jpg 并查看它是否显示图像。那应该是正确的地址。同样在代码中,编写img 标记,如&lt;img src="/{{ image.image.url }}" height="420"&gt;,在url 前使用斜杠字符。好的,看看这是否可行。
  • localhost:8000/media/images/albums/photo_4.jpg url 不显示图片。我收到 404 错误。但是 img 标签中的“/”是个好主意。 URL 似乎是正确的。但无法加载静止图像。
  • 您尝试过我的回答吗? MEDIA_ROOT='/media/'

标签: python django image django-templates django-models


【解决方案1】:

检查您的 settings.py,您已经定义了 MEDIA_ROOT 和 'MEDIA_URL'(它们是正确的)。 MEDIA_ROOT 指定计算机上将存储媒体的绝对文件夹。

举个例子:

MEDIA_ROOT = '/myfolder/'

这意味着它将在以下位置查找图像:

/myfolder/images/albums/

接下来在您的 settings.py 中检查您的 MEDIA_ROOT 位置:即

MEDIA_URL = 'http://localhost/myfolder/'

所以你的图片:

<img src="{{ MEDIA_URL }}{{ image.image.url }}" height="420"></a>

这将涉及:

http://localhost/myfolder/images/albums/

希望这会有所帮助。

【讨论】:

  • 当我更改 MEDIA_URL 并将其添加到 src 时,图像 url 更改为:localhost:8000/media/http://localhost:8000/media/images/albums/…。但是当 MEDIA_URL = '' 时很好。所以它并没有解决问题。
  • MEDIA_URL 必须是指向同一目录路径的 URL。使用 url 属性时不需要 {{ MEDIA_URL }},因为它会自动附加 MEDIA_URL 但您确实需要设置 {{ MEDIA_URL }} 否则您的图像将不会显示!
【解决方案2】:

如果您使用的是开发服务器,那么您需要在 urls.py 中添加一些内容以使 django 为媒体文件提供服务,参见:

1.4.x:https://docs.djangoproject.com/en/1.4/howto/static-files/#serving-other-directories 1.5.x:https://docs.djangoproject.com/en/dev/howto/static-files/#serving-files-uploaded-by-a-user

【讨论】:

  • @Sheshkovsky :帮自己一个忙,去阅读这些链接。
【解决方案3】:

我知道问题出在哪里。 MEDIA_URL 应该是这样的:

MEDIA_ROOT='<the full path to your media folder>' (i.e: '/home/ike/project/media/')
MEDIA_URL='/media/'

注意开头的斜线字符。那是因为 media 是您的根服务器文件夹中的一个文件夹,与您调用的任何其他 url 无关。

并将这些行添加到您的 urls.py 文件的末尾:

# You might need to import static function like this:
#from django.contrib.staticfiles.urls import static

urlpatterns += staticfiles_urlpatterns()
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

您可以查看以下文档:https://docs.djangoproject.com/en/dev/howto/static-files

希望对你有帮助

【讨论】:

  • 我收到一个错误,因为 staticfiles_urlpatterns 未定义。有什么想法吗?
  • @AswinMurugesh:将此行添加到您的urls.pyfrom django.contrib.staticfiles.urls import staticfiles_urlpatterns
  • 我得到'name 'static' is not defined'
  • @AnselZandegran 添加这个:from django.contrib.staticfiles.urls import static
【解决方案4】:

在您的 details.html 中,更改您的

img src="{{ image.image.url }}" height="420"

img src="your_app/media/{{ image.image.url }}" height="420"

我希望这会有所帮助。如果不是,我很乐意提供更多详细信息。

【讨论】:

  • 我不认为硬编码静态 url 是个好主意。为什么不加载静态模板标签{% load static %} 或使用{{ STATIC_URL }}
【解决方案5】:

来源:https://docs.djangoproject.com/en/dev/howto/static-files/#serving-files-uploaded-by-a-user

 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)

您需要添加到 url 模式以提供上传的文件

【讨论】:

    【解决方案6】:

    我从上面的每个答案中提取了一点。我遇到了和你一样的问题。我得到了来自当前 /blog/post/(media_url)/image.jpg 的回报

    在我的管理门户中,我可以轻松查看和编辑它。但是在我的 post.html 上我遇到了问题,直到我添加了 {{ MEDIA_URL }} --

    这就是我所缺少的。

    我在下面发布了我的整个部分,以便其他人可以阅读它并查看他们缺少的内容。

    post.html:
    
        <label for="id_image">  <img src="{{ MEDIA_URL }}{{ p.image.url }}" 
        title="{{ p.title }}"> </label>
    
    models.py:
    
        from django.core.files.storage import FileSystemStorage
    
        upload_location =
        FileSystemStorage(location='/home/pi/djcode/xpcpro/xpcpro/images')
    
        class Blog(models.Model):
            title = models.CharField(max_length=255)
            author = models.ForeignKey(settings.AUTH_USER_MODEL, default=1)
            date = models.DateTimeField(auto_now=False, auto_now_add=True)
            body = models.TextField()
            image = models.ImageField(
                storage=upload_location, null=True,
                blank=True, width_field="width_field",
                height_field="height_field",)
            height_field = models.IntegerField(default=0)
            width_field = models.IntegerField(default=0)
    
    urls.py:
    
        from django.conf.urls.static import static
        from django.contrib.staticfiles.urls import staticfiles_urlpatterns
    
        urlpatterns += staticfiles_urlpatterns()
        urlpatterns += static(settings.MEDIA_URL,
        document_root=settings.MEDIA_ROOT)
    
    settings.py:
    
        MEDIA_ROOT = "/home/pi/djcode/xpcpro/xpcpro/images/"
        MEDIA_URL = "/images/"
    

    【讨论】:

      【解决方案7】:

      好吧,我知道这个问题很老,但在证明所有选项后我现在就解决了:

      1. settings.py:
      MEDIA_URL = '/媒体/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
      1. urls.py 危险!!!我的错误之一是我使用了 my_app/urls.py ... /li>
      从 django.conf.urls.static 导入静态 从 django.contrib.staticfiles.urls 导入 staticfiles_urlpatterns 从 django.conf 导入设置 urlpatterns += staticfiles_urlpatterns() urlpatterns += 静态(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT)
      1. 您的模板,detail.html
      img src="{{ image.image.url }}" alt="{{ image.title }}"

      注意事项: 哟不需要 MEDIA_URL,小心 '/' 因为 image.image.url 是绝对的,所以如果你使用命名空间,那么你不需要添加结束斜线。

      img src="/namespace_name/{{ image.image.url }}" --> 不好!!! img src="/namescape_name{{ image.image.url }}" --> 好!!!

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-12-23
        • 1970-01-01
        • 1970-01-01
        • 2016-06-25
        • 2015-01-08
        • 2014-08-31
        • 2013-04-11
        • 1970-01-01
        相关资源
        最近更新 更多