Getting the url in the view

瀏覽次數:142 次
跳到第一則未讀訊息

Manuel González

未讀,
2013年9月27日 下午6:23:412013/9/27
收件者:django-...@googlegroups.com
Hi there, 

     I have been using django imagekit without any problems in the templates but now I need to get the url in the view not the template, following your example in the imagekit docs:
source_file = open('/path/to/myimage.jpg')
image_generator = Thumbnail(source=source_file)
result = image_generator.generate()
So I did this:
course_img = open(settings.MEDIA_ROOT+str(course.image), 'rb+') 	
image_generator = myapp_images.Thumbnail100x100(source=course_img)
result = image_generator.generate()
And then, I try to get the url from the "result" variable, but I don't know how:
details_html += "<img class='img-rounded' src='"+ str(result) +"'/>
I have been trying with str(result), result.url, result.name, etc... with no luck, any idea how to get it?
Thx

matthewwithanm

未讀,
2013年9月27日 晚上9:03:222013/9/27
收件者:django-...@googlegroups.com
Hey Manuel!

Image generators are used for generating PIL image objects. On the other hand,
the model fields and template tags are returning File-like objects that
represent the cached image file. These File-like objects wrap your image
generators, which they use to generate the image when needed. This separation
gives us a couple of pretty cool things. For one, we can use image generators
completely separate of the caching layer. You can think of image generators as
defining how an image is made, and the wrapper as determining when to make
the image, and how to save it.

In your case, you want to interact with a cache file, so you need to wrap your
generator with an ImageCacheFile, like this:

from imagekit.cachefiles import ImageCacheFile
image_generator = myapp_images.Thumbnail100x100(source=course_img)
result = ImageCacheFile(image_generator)

That result object is what you're expecting—a File-like object with a url
attribute.

Your code can also be simplified a little: the source kwarg that gets passed
to the image generator needs to be another File-like object. In the docs, I use
open to show one way of getting a File-like object, but you can really get it
from anywhere. In your case, it looks like you want to use an ImageField from a
model—but those are actually already File objects! So you can just do this:

from imagekit.cachefiles import ImageCacheFile
image_generator = myapp_images.Thumbnail100x100(source=course.image)
result = ImageCacheFile(image_generator)

Not only does this eliminate that extra call to open, it avoids the use of
MEDIA_ROOT, which is kind of icky here. (If you were to every change your
media storage backend, course.image would still get you the file, but using
MEDIA_ROOT like that wouldn't.)

Hope this helps!
回覆所有人
回覆作者
轉寄
0 則新訊息