0
votes

I have the following model containing an image field that I want to show up in my template show_item.html.

Models.py

class Item(models.Model):
    def get_file(self, filename):
        url = "%s/%s" % (settings.MEDIA_ROOT, filename)
        return url

    seller = models.ForeignKey(settings.AUTH_USER_MODEL)
    pic1 = ImageField(blank=True, upload_to=get_file, max_length=500)

I know that MEDIA_ROOT and MEDIA_URL are properly configured.

The problem is that in my template, I try to access

 <img src="{{ item.pic1 }}">

which fails to be found. Upon further investigation, this is because the path is showing up as the one in my file directory (e.g. /home/user/apps/media/filename) rather than the media_url (e.g. www.mysite.com/media/filename). I checked both locations and the image is in fact in both.

My question -- how do I access the url of the form www.mysite.com/media/filename in the template? I've tried {{ item.pic1.url }} as well, but it's still the path on my system.

Thanks!

1

1 Answers

0
votes

If your image uploaded path can be accessed by the static path, just use the static url. Or else I think you may write a url, pointing to a view to return the image response.

For example:

# in your urls.py
urlpatterns = patterns('',
    url(r'^image/(?P<pk>\d+)/$', 'image_view', name='image_view'),
)

and then response the image content in the image view.

from django.core.servers.basehttp import FileWrapper
from django.http import StreamingHttpResponse

def image_view(request, pk):
    item = Item.objects.get(pk=pk)
    filename = item.pic1.url
    wrapper = FileWrapper(open(filename, 'rb'))
    response = StreamingHttpResponse(wrapper)
    response['Content-Length'] = os.path.getsize(filename)
    response['Content-Disposition'] = 'attachment; filename=image.jpg'
    return response