I have the following django model with an ImageField:
class Pics(models.Model):
def file_path(instance, filename):
return '/'.join([instance.user.username, 'pics', filename])
#...
file = models.ImageField(upload_to=file_path)
I know I can call pic.file.url to get the url to the image. however, I’m wondering if Django also implements some functionality to automatically host that image?
The code I have currently works fine but it seems redundant:
#urls.py
urlpatterns += patterns('views',
url(r'media/(?P<name>\w{1,30})/pics/(?P<file>[^\\/:*?\"<>|]+)$', 'show_pic'),)
then my view is:
#app.views
import mimetypes
def show_pic(request, name, file):
path = u'media/%s/graphics/%s' % (name, file)
mime = mimetypes.guess_type(name)[0]
image_data = open(path, 'rb').read()
return HttpResponse(image_data, mimetype=mime)
Instead of creating a view to serve the pictures you can directly point to
media/<name>/graphics/<file>and let your webserver itself serve the images. Django is not well suited for serving static files, but your webserver on the other hand is designed to handle them efficiently.