In some cases you would want to have “private” images for your logged-in users, you will not be able to store the images in the public accessible directory.

For example, if you have “my_private_photo.png” stored in your normal “images” directory, any user (logged in or not) will be able to do this in the URL bar:

http://www.yourwebsite.com/images/my_private_photo.png

When an anonymous user does that, he would be able view the private image.

To do this, you must store your “private images” outside the public accessible directory. In this example, we will put the private images in:

/home/wenbert/private_storage

Before I proceed, please take note that this example will use X-Sendfile. Please refer to my post on how to install and configure X-Sendfile in your Apache webserver.

Now for the view.py, it would look something like this:

def display_image ( request , image_id ) : path = "/home/wenbert/private_storage" file = image_id filepath = os . path . join ( path , file ) #Here, you put your code to check whether the user has access to this photo or not response = HttpResponse ( mimetype = mimetypes . guess_type ( filepath ) ) response [ 'Content-Disposition' ] = 'filename="%s"' %smart_str ( file ) response [ "X-Sendfile" ] = filepath response [ 'Content-length' ] = os . stat ( filepath ) . st_size return response

In your urls.py, you would want to add something like this:

( r '^display_image/(?P<image_id>d+)/$' , display_image )

With this, you should be able to output images through your templates using the normal IMG tag. For example:

<img src="/display_image/private_photo.png" />

Note that I have hard-coded “private_photo.png”. This is assuming I already know the “image id” you want to display.

Comments/questions/suggestions, do not hesitate to post them below.

I hope that was helpful.