Display an image located in the database in Django

2020-06-04 13:11发布

I just want to display an image that i have uploaded through the admin module, through an html image tag on a web page. The image is located in /home/user/work/djcode/media/chicks/blondie.jpg.

Here is the relevant part of my models.py

class Image(models.Model):
    model_name = models.CharField(max_length=50)
    model_pic = models.ImageField(upload_to='chicks/')
def __unicode__(self):
    return self.model_name

Here is is the relevant part of my views.py

def main(request):
    i = get_object_or_404(Image, pk=1)
    return render_to_response('polls/main.html', {'image': i}, context_instance=RequestContext(request))

The html tag that i am using is simply

<img src="{{ MEDIA_ROOT }}/{{ image.model_pic.url }}">

From settings.py, my media root is MEDIA_ROOT = '/home/user/work/djcode/media'

Note that the variable {{ image.model_pic.url }} shows "chicks/blondie.jpg" through the html template so I think that my image object is indeed well sent to the template.

Anyone could give me a hand with that ? That would be really helpful.

Thanks a lot for your time!

2条回答
够拽才男人
2楼-- · 2020-06-04 13:39

You need to use {{MEDIA_URL}} or {{STATIC_URL}} , the choice depends on how you manage your files on server.

查看更多
太酷不给撩
3楼-- · 2020-06-04 13:40

Your use of the url function on the image field in your template is not quite correct - {{ image.model_pic.url }} should fix the issue. You just need to drop the {{ MEDIA_URL }} bit.

Your html should be -

<img src="{{ image.model_pic.url }}">

Have a look at the documentation on using files in models.

If you're still having trouble then it may be an issue with serving static files. Serving static files in django varies depending on whether you're doing it in production or just using the python manage.py runserver command.

To server media files during development (with python manage.py runserver), make sure you've got your MEDIA_URL and MEDIA_ROOT correct in your settings.py then you can append the following to your url conf -

from django.conf import settings
from django.conf.urls.static import static

urlpatterns = patterns('',
    # ... the rest of your URLconf goes here ...
) + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

Have a look at the docs for instructions on how to serve files in production.

查看更多
登录 后发表回答