1

views.py

def f_page(request, slug, f_slug):
  f = get_object_or_404(F, slug= f_slug)
  if f:
     events = f.event_set.order_by('-pub_date')
     if events:
       for event in events:
       comments = event.comment_set.order_by('-pub_date')
  variables = RequestContext(request, {
     'f' : f,
     'events' : events,
     'comments' : comments,
  })
  return render_to_response('f_page.html', variables)

Here events and comments are iterables. Each f has multiple events and then each event has multiple comments. The problem is how do I render this in my html page.I have tried this but it didn't work:

{% for event in events %}
    <a href="/{{ event.author.username }}/">{{ event.author.first_name }}</a>
    {{ event.pub_date }}
    {{ event.description }}
    {% for comment in comments %}
        {{ comment }}
        {{ comment.author.first_name }}
    {% endfor %}
{% endfor %} 

The events part shows up right but the comment set doesn't show up. My models work just fine I have tried everything in the admin panel. I can see where I'm messing it up but am unable to solve it. In 'views.py' the comments object for each event is not being saved. But, I don't know how to resolve it. Please help. Thanks in advance.

1 Answer 1

3

Instead of passing comments to template you can get it in template.

{% for event in events %}
    <a href="/{{ event.author.username }}/">{{ event.author.first_name }}</a>
    {{ event.pub_date }}
    {{ event.description }}
    {% for comment in event.comment_set.all %}
        {{ comment }}
        {{ comment.author.first_name }}
    {% endfor %}
{% endfor %} 

Add ordering field in your models Meta class so that event.comment_set.all gives you data in your order.

class Comment(Model):
   ...
   class Meta:
        ordering = ['-pub_date']
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks! It works right. Does making queries in the template have any performance issue?
@Monica, Don't think there is performance issue. Also, a problem with your code is you want list of comments for each event, but you are storing only one (last one).

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.