Django:MEDIA_URL未设置在模板中 [英] Django: MEDIA_URL not set in template

查看:223
本文介绍了Django:MEDIA_URL未设置在模板中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经阅读了很多问题和文章,但找不到我失踪的内容。



这是我的conf:



settings.py

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

STATIC_URL ='/ static /'

STATICFILES_DIRS =(
os。 path.join(os.path.dirname(__ file __),'static')。replace('\\','/'),

pre>

urls.py

  urlpatterns = [
url(r'^ $',include('home.urls')),
url(r'^ admin /',include(admin.site.urls)),
url(r'^ artist /',include('artists.urls')),
url(r'photo /',include('photo.urls'))
]
urlpatterns + = staticfiles_urlpatterns()
urlpatterns + = static(settings.MEDIA_URL,document_root = settings.MEDIA_ROOT)

无论我的媒体如何,当我去 http:// localhost:8000 / media / path / to / image.jpg 我的形象。



但是,当我在模板中,我就像这样:

 < img class =avatar secondary-contentsrc ={{MEDIA_URL}} {{artist.artist_image}}> 

我只有图像路径。当我通过'/ media /'更改html {{MEDIA_URL}} 时,它可以工作。



所以它似乎我的 MEDIA_URL 没有设置在模板中,就我所搜索的,我看不到我错过的东西。


$ b $我在django 1.8.2。如果您需要任何信息,请问我。

解决方案

models.ImageField 有一个名为 url 的属性,可以让您浏览图像的路径。



您应该使用 artist.artist_image.url 而不是手动将 MEDIA_URL 添加到您的图像名称中:

 < img class =avatar secondary-contentsrc ={{artist.artist_image.url}}/> 

-



确保 artist_image 不是,否则调用 .url 引发异常。


I've read a lot of question and article but can't find what I'm missing.

Here is my conf :

settings.py

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

STATIC_URL = '/static/'

STATICFILES_DIRS = (
    os.path.join(os.path.dirname(__file__),'static').replace('\\', '/'),
)

urls.py

urlpatterns = [
    url(r'^$', include('home.urls')),
    url(r'^admin/', include(admin.site.urls)),
    url(r'^artist/', include('artists.urls')),
    url(r'photo/', include('photo.urls'))
]
urlpatterns += staticfiles_urlpatterns()
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

Whatever, my media are served, cause when I go to http://localhost:8000/media/path/to/image.jpg, i have my image.

But when in template I go like this :

<img class="avatar secondary-content" src="{{MEDIA_URL}}{{artist.artist_image}}">

I only have the image path. When I change in html {{MEDIA_URL}} by '/media/', it works.

So it seems my MEDIA_URL is not set in template and as far as I've searched, I can't see what I missed.

I'm on django 1.8.2. If you need any informations, just ask me.

解决方案

models.ImageField has a property called url which gives you the browsable path of your image.

You should be using artist.artist_image.url instead of prepending MEDIA_URL to your image name manually:

<img class="avatar secondary-content" src="{{artist.artist_image.url}}" />

--

Make sure artist_image is not None, otherwise calling .url throws an exception.

这篇关于Django:MEDIA_URL未设置在模板中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆