简体   繁体   English

Django管理员提供上传的图片

[英]Django admin serving uploaded image

I am new to Django I'm stuck with regards to how I can fix this issue. 我是Django的新手,我对如何解决此问题感到困惑。

I have aa model which contains an ImageField as follows 我有一个包含ImageField的模型,如下所示

name = models.CharField(max_length=100)
description = models.CharField(max_length=1000)
file = models.ImageField(upload_to='img')

and then in my settings.py I have 然后在我的settings.py中

STATIC_ROOT = os.path.join(PROJECT_PATH, "static")
STATIC_URL = '/static/'

MEDIA_ROOT = os.path.join(PROJECT_PATH, 'media')
MEDIA_URL = 'media/'

and I have the following url pattern to handle this 我有以下网址格式来处理此问题

 url(r'^media/(?P<path>.*)$', 'django.views.static.serve', {
                            'document_root': settings.MEDIA_ROOT, 'show_indexes' : True
                            })

In the admin pages I am able to upload the image perfectly fine to the expected location in the media folder, and I am able to access this by loading 127.0.0.1:8000/media/img/my_image.jpg. 在管理页面中,我可以将图像完美地上传到媒体文件夹中的预期位置,并且可以通过加载127.0.0.1:8000/media/img/my_image.jpg来访问该图像。 The problem is that in the standard admin panel the link which shows the currently uploaded image for the object simply appends media/img/my_img.jpg to the end of the current URL and therefore receives a 404. 问题在于,在标准管理面板中,显示对象当前上载图像的链接只是将media / img / my_img.jpg附加到当前URL的末尾,因此会收到404。

I am not sure what the best way to fix this issue is, I Hope this makes sense and please let me know if more information is needed. 我不确定解决此问题的最佳方法是什么,我希望这是有道理的,如果需要更多信息,请告诉我。

Thanks. 谢谢。

Change 更改

MEDIA_URL = 'media/'

to

MEDIA_URL = '/media/'

and it should stop appending to the URL and replace it instead. 并且应该停止附加到URL并替换它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM