1

Suppose I have a model Photo with an ImageField.

I tried to iterate all photo objects in a template by {% for photo in Photo.objects.all %}.
Nothing comes up.

Is this impossible?

1
  • Please show your view's code. As Preet said, templates don't get direct access to models; they only get what's in the context plus anything middleware adds. Commented May 7, 2012 at 5:37

2 Answers 2

6

The usual way this is done is with a view that looks something like:

def photo_view(request):
    return render_to_response('app_name/photos.html', {
        'photos': Photo.objects.all()
        })

And then the template (in app_name/templates/app_name/photos.html in this example) has something like:

{% for photo in photos %}

If you really want to do {% for photo in Photo.objects.all %}, then your view code must pass Photo via the context:

def photo_view(request):
    return render_to_response('app_name/photos.html', {
        'Photo': Photo
        })

Bear in mind that this is not really any better of a way to do it, as template syntax is a lot more restrictive than Python. For example, there is no way to do {% for photo in Photo.objects.filter(...) %} in the template; the filtering needs to happen in the view.

Sign up to request clarification or add additional context in comments.

Comments

3

You might be thinking about it the wrong way.

The HTTP request gets routed to a view.

The view does any business logic (which may involve accessing the DB via ORM), and then passes any required data/objects as a context dictionary to the templating system.

The templating system only sees what it has been passed from the view. If the object is a lazily-evaluated ORM DB iterator, then sure, it can access DB. But the view must pass that object into the template's context.

Try {{Photo}} in your template to make sure it is actually being passed an object named "Photo" by the corresponding view. You may need to inspect source of the generated html (in case due to its repr it does something weird with angle brackets and doesn't display properly in your browser.)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.