How to show an image in template uploaded from admin panel Django 1.3

折月煮酒 提交于 2019-12-08 12:33:26

问题


I'm a newbie to django. I'm developing a project in django 1.3. Problem is I'm uploading a image from the admin panel

class About(models.Model):

    image = models.ImageField(upload_to='about')
    files = models.FileField(upload_to='about')

Here is my template tag

<img class="profile_pic" src="{{ about.image }}" />

My setting file is as below

MEDIA_ROOT = path("media/")
MEDIA_URL = '/media/'
STATIC_ROOT = ''
STATIC_URL = '/static/'
ADMIN_MEDIA_PREFIX = '/static/admin/'
STATICFILES_DIRS = (
    path('static/'),
)

I checked that image is uploaded to /media/about/image_name. Problem is it rendered in the template as "/about/imagename" but not shoing. When I manually go to that image url it showing a 404 error.


回答1:


<img class="profile_pic" src="{{ about.image.url }}" />

UPDATE

Also in your urls.py:

if settings.DEBUG:
    urlpatterns += patterns('',
        (r'^' + settings.MEDIA_URL.lstrip('/'), 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT})



回答2:


It worked!... After importing setting.MEDIA_ROOT in the urls.py file then I added a media rule so ITs working now..

BTW It also need

{{ about.image.url }} 

as @zsquare(thanks) said earlier Here is the media rule

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


来源:https://stackoverflow.com/questions/6800166/how-to-show-an-image-in-template-uploaded-from-admin-panel-django-1-3

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!