On Wed, May 14, 2008 at 6:33 PM, John <[EMAIL PROTECTED]> wrote:
>
> I'm having trouble accessing dictionary elements within a nested for
> loop.  here are some code snippets:
>
> [...]
>
> # so far so good, but then I try to iterate over the documents and
> their associated tags in a template
> # here is the template with the html stripped out for readability
> {% for document in documents %}
>  {{ document.content }}
>  {% for doctag in tag_dict[document.uid] %} {{ doctag.tagid }} {%
> endfor % }
> {% endfor %}
>
> # document.content is fine, but when I try to access tag_dict within
> the template's for loop, it complains:
> TemplateSyntaxError: Could not parse the remainder: [document.uid]

right, templates are not python :) you can't do that, and it's on
purpose: that kind of fiddling around with the model is best done in
the view, not in the template.

So... instead of doing e.g.

documents = Document.objects.all()
tag_dict = {}
for document in documents:
    tag_dict[document.uid] = DocumentTag.objects.filter(docid=document.uid)

and passing those two into the template, you could do something along
the lines of

documents = [dict(object=document,
                  tags=DocumentTag.objects.filter(docid=document.uid))
             for document in Document.objects.all()]

and then in the template, you do

{% for document in documents %}
  {{ document.object.content }}
  {% for doctag in document.tags %} {{ doctag.tagid }} {% endfor %}
{% endfor %}

this is assuming there is some reason for you not to modify the
Document class to give it the appropriate methods or attributes to
access the related DocumentTag directly; if you could do that, life
would be much easier :)

-- 
John Lenton ([EMAIL PROTECTED]) -- Random fortune:
The trouble with a lot of self-made men is that they worship their creator.

--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com
To unsubscribe from this group, send email to [EMAIL PROTECTED]
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en
-~----------~----~----~----~------~----~------~--~---

Reply via email to