Search code examples
djangodevelopment-environmentproduction-environment

django - strange template loop failure between dev/prod environment


I'm working on a django app for a site that requires an image gallery. Since the site is fairly simple I chose not to use a database. In the gallery part, I have a loop in the view that reads all the image files from the image folder, and sends them to the template, where they are rendered inside a loop:

import os
from django.shortcuts import render_to_response

def show_pics(request):
    """sends a list of files to the view"""
    folder = '/static/images'
    files = [os.path.join(folder, f) for f in os.listdir(folder) if '.jpg' in f]
    return render_to_response('gallery.html', { 'files' : files })

and the template:

<div id="gallery">
    {% for file in files %}
        <img src="{{ file }}" class="gallery-image" />
    {% endfor %}
</div>

This works great in development mode (I set up url to serve static files under '/static/'), but when I upload to my webserver, the images aren't rendered. When I look at the rendered html, this is what I get:

<div id="gallery">  </div>

I made sure the static url works on the webserver by trying to access some random picture through the static url - http://mysite.com/static/images/some_image.jpg, and the css is definitely working (don't worry, I'll use a separate server for static files later). I should probably say that the production server is running python2.5 whereas I'm running 2.6 (both have django 1.1). Any thoughts?


Solution

  • It's safe to assume files is empty in template. You can confirm this by putting {{ files }} in the template and see what it prints. Most likely, nothing.

    However, there are few possible problems with this:

    folder = '/static/images'
    files = [os.path.join(folder, f) for f in os.listdir(folder) if '.jpg' in f]
    

    First, the path os.listdir takes is not the path from your document root, but from file system root. So if you do ls /static/images on the server, what does it show?

    And as a minor thing, I'd prefer using f.endswith('.jpg')