Reputation: 71
Friends, I am trying to implement a question answer site in which a logged in user gets a list of questions and answers asked by the users he follows. I am using django-friendship to implement user follows. I want to know how we can fetch all the questions posted by the users whom the current user follows.
I have tried the following but doesn't work.
views.py
def index(request):
if request.session.get('current_user'):
questions = []
users = Follow.objects.following(request.user)
i = 0
while i < len(users):
posts = Question.objects.filter(user=users[i])
questions.append(posts)
i = i + 1
return render(request, "welcome/index.html",locals())
Here's my template
welcome/index.html
{% extends "layout.html" %}
{% block content %}
{% for q in questions %}
{{ q.title }}
{% endfor %}
{% endblock %}
Upvotes: 0
Views: 41
Reputation: 2798
You can fetch all questions without looping
views.py
def index(request):
if request.session.get('current_user'):
users = Follow.objects.following(request.user)
questions = Question.objects.filter(user__in=users)
return render(request, "welcome/index.html",locals())
template
{% extends "layout.html" %}
{% block content %}
{% for q in questions %}
{{ q.title }}
{% endfor %}
{% endblock %}
Upvotes: 0
Reputation: 73470
posts
is a queryset. Thus, questions
is a list of querysets and, in your template, you are not iterating over Question
instances, but querysets that do NOT have a title
attribute. You can try in your view:
questions.extend(posts) # not: append
in order to obtain an actual list
of Question
instances. Or, you can change your template:
{% for qs in questions %}
{% for q in qs %}
{{ q.title }}
{% endfor %}
{% endfor %}
Upvotes: 0