Django - accessing url of an imageField that corresponds to media_url not media_root -


i have following model containing image field want show in 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 media_root , media_url configured.

the problem in template, try access

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

which fails found. upon further investigation, because path showing 1 in file directory (e.g. /home/user/apps/media/filename) rather media_url (e.g. www.mysite.com/media/filename). checked both locations , image in fact in both.

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

thanks!

if image uploaded path can accessed static path, use static url. or else think may write url, pointing view return image response.

for example:

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

and response image content in image view.

from django.core.servers.basehttp import filewrapper 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 

Comments

Popular posts from this blog

commonjs - How to write a typescript definition file for a node module that exports a function? -

openid - Okta: Failed to get authorization code through API call -

ios - Change Storyboard View using Seague -