views:

51

answers:

1

I have a mini blog app, and a reply system. I want to list all mini blog entries, and their replies, if there are any. i have in views.py

def profile_view(request, id):
        u = UserProfile.objects.get(pk=id)
        paginator = New.objects.filter(created_by = request.user) 
        replies = Reply.objects.filter(reply_to = paginator)
    return render_to_response('profile/publicProfile.html', {
        'object_list': u,
        'list':paginator,
        'replies':replies
        }, 
        context_instance=RequestContext(request)) 

and in the template:

<h3>Recent Entries:</h3>
     {% for object in list %}
<li>{{ object.post }} <br />
{% for object in replies %}
{{ object.reply }} <br />
{% endfor %}

mention : reply_to is a ForeignKey to New, and New is the name of the 'mini blog' table

But it only shows all the replies for each blog entry, not the reply for every entry, if there is one

thanks

+3  A: 

Firstly, please consider giving your variables sensible names. New, list and paginator do not at all describe what those objects actually are - and in some cases they are actively misleading, as with object_list which is not a list at all but a single item.

Secondly, the code is doing exactly what you asked it to (ignoring the fact that the template code you have posted is actually invalid, because you are not nesting the loops properly and redefine the object variable). You get all entries, and all replies, then show the list of all replies underneath every entry.

Instead, you obviously want to get the replies attached to each entry. So delete the lines referring to Reply in the view, and in the template make use of the reverse relationship:

{% for object in list %}
  {{ object.post }}
  {% for reply in object.reply_set.all %}
    {{ reply }}
  {% endfor %}
{% endfor %}

Finally, as others have recommended in answer to your other questions, you would be well served by reading the Django tutorial and the Django book, both available freely online.

Daniel Roseman
yes. you're perfectly right.thanks!
dana