Python 来自 Django ImageField 的图像不会加载到模板中

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16196603/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 22:00:21  来源:igfitidea点击:

Images from ImageField in Django don't load in template

pythondjangoimagedjango-templatesdjango-models

提问by sheshkovsky

I'm building a gallery using Django(1.5.1) on my local machine. In my Album model I have a ImageField. There is a view to show all images of an album. It works well, but at the end images don't show up. There's border of images as you can see but images don't load.

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

screenshot

截屏

enter image description here

在此处输入图片说明

models.py

模型.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

视图.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

详细信息.html

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

If this is my album address: http://localhost:8000/gallery/1/

如果这是我的专辑地址: http://localhost:8000/gallery/1/

Then image URL is:http://localhost:8000/media/images/albums/photo_4.JPG (I get 404 when enter it in browser)

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

This media root and url:

此媒体根目录和网址:

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

My media root has 777 permission.

我的媒体根有777 权限

What should I do now? Where is the problem?

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

采纳答案by Paulo Bu

I have a clue on what's the problem. MEDIA_URLshould be like this:

我有什么问题的线索。MEDIA_URL应该是这样的:

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

Note the slash character at the beginning. That is because media is a folder in your root server folder and not relative to whatever other url you call it.

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

And add these lines to the end of your urls.pyfile:

并将这些行添加到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)

You can check the following documentation: https://docs.djangoproject.com/en/dev/howto/static-files

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

Hope this helps

希望这可以帮助

回答by Glyn Hymanson

Check in your settings.pyyou have define MEDIA_ROOTand 'MEDIA_URL' (and they are correct). The MEDIA_ROOT specifies an absolute folder on your machine where media will be stored.

检查您定义的settings.pyMEDIA_ROOT和“MEDIA_URL” (它们是正确的)。MEDIA_ROOT 指定您机器上将存储媒体的绝对文件夹。

So for an example:

举个例子:

MEDIA_ROOT = '/myfolder/'

This would mean it would look for image at:

这意味着它会在以下位置寻找图像:

/myfolder/images/albums/

Next in your settings.pycheck your MEDIA_ROOTlocation: i.e.

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

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

So your images:

所以你的图像:

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

This would relate to:

这将涉及:

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

Hope this helps.

希望这可以帮助。

回答by bruno desthuilliers

If you're using the dev server then you need to add something to your urls.py to make django serve the media files, cf:

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

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

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/静态文件/#serving-files-uploaded-by-a-user

回答by Amimo Benja

Within your details.html, change your

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

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

To

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

I hope this helps. If not I will be glad to provide more details.

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

回答by Saher Ahwal

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

来源: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)

you need to add to url pattern to serve uploaded files

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

回答by jMrL

I took a little from each of the answers above. I was having the same problem as you. I was getting returns that were being directed from the current /blog/post/(media_url)/image.jpg

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

In my admin portal I could view it easily and edit it. But on my post.html I was having problems until I added the {{ MEDIA_URL }} --

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

That is all that I was missing.

这就是我所缺少的。

I posted my entire section below so that other people could read it and see what they are missing.

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

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/"

回答by Leaf

Well I know this question is old but I solved it right now after prove all options:

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

  1. settings.py:
  1. 设置.py:
    MEDIA_URL = '/media/'
    MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
  1. urls.py DANGER!!! Here one of my errors was that I used my_app/urls.py... If you want to use my_app/urls.py you need to add "/namespace_name{{ image.image.url }}" to img' src:
  1. urls.py 危险!!!这里我的错误之一是我使用了 my_app/urls.py...如果你想使用 my_app/urls.py 你需要添加“/namespace_name{{ image.image.url }}”到 img' src:
    from django.conf.urls.static import static
    from django.contrib.staticfiles.urls import staticfiles_urlpatterns
    from django.conf import settings

    urlpatterns += staticfiles_urlpatterns()
    urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
  1. Your template, detail.html
  1. 你的模板,detail.html
    img src="{{ image.image.url }}" alt="{{ image.title }}"

NOTES: Yo don't need MEDIA_URL, be careful with the '/' because image.image.url is absolute, so if you use a namespace then you don't need to add the finish slash.

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

    img src="/namespace_name/{{ image.image.url }}"  --> BAD!!!
    img src="/namescape_name{{ image.image.url }}"   --> GOOD!!!