Display image located in database in Django

I just want to display the image that I uploaded through the admin module through the html image tag on the web page. Image is 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 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 I'm using is just

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

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

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

Can anyone give me a hand with this? That would be very helpful.

Thanks so much for your time!

+6
source share
2 answers

Your use of the url function in the image field in your template is not entirely correct - {{ image.model_pic.url }} should fix this problem. You just need to reset the bit {{ MEDIA_URL }} .

Your html should be -

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

See the documentation for using files in models .

If you still have problems, you may encounter a problem with the static file service. Serving static files in django depends on whether you do this during production or just use the python manage.py runserver .

For media server files at design time (using python manage.py runningerver) make sure you have your MEDIA_URL and MEDIA_ROOT in your .py settings, then you can add the following to your conf url

 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) 

Check out the docs for instructions on how to maintain files during production.

+5
source

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

+1
source

All Articles