Reputation: 103
I am trying to pass a custom query to a template but the query results are not being displayed.
I had a working solution for this but I wanted to implement a custom model manager to simplify the code but I cant get the final step work - that is displaying the results on the template
I have a custom manager:
from django.db import models
class ProfileQuerySet(models.QuerySet):
def get_users_follows(self, user):
print(user)
return self.filter(followed_by__user__username=user)
class ProfileManager(models.Manager):
def get_queryset(self):
return ProfileQuerySet(self.model, using=self._db)
def get_users_follows(self, user):
return self.get_queryset().get_users_follows(user)
which is instantiated in the model:
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
image = models.ImageField(default='default.jpg', upload_to='profile_pics')
follows = models.ManyToManyField('self', related_name='followed_by', symmetrical=False)
objects = ProfileManager()
my view is as follows:
class FollowsListView(LoginRequiredMixin, ListView):
# Follow.follow_data = [[],[]]
model = Profile
template_name = 'blog/follows.html' # <app>/<model>_<viewtype>.html
# paginate_by = 6
def get_queryset(self):
follow_data = Profile.objects.get_users_follows(self.request.user)
context = {'follow_data', follow_data}
return context
In the template i am calling the follow_data like so:
{{ follow_data }}
{% for p in follow_data %}
{% if p.user %}
<article class="media content-section">
<img class="rounded-circle article-img" src="{{ p.user.profile.image.url }}" alt="">
<a href="{% url 'user-posts' p.user %}">{{ p.user.profile.user }}</a>
{% else %}
<p>You are not following any users</p>
{% endif %}
</article>
{% endfor %}
but no results are being displayed so I am not quite sure what I am doing wrong here. Can anyone provide me weith a quick pointer on what ive done wrong?
Upvotes: 1
Views: 933
Reputation: 2589
There is a typo:
context = {'follow_data', follow_data}
You've created a set, but what you really want is a dict
context = {'follow_data': follow_data}
edit:
but you shouldn't be returning a context here anyway, you should return a queryset. simply do return follow_data
should work.
in your template, you can refer to the queryset with {% for user in object_list %}
If you don't want to call it "object_list" you'll need to override get_context_data
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context["follow_data"] = context.pop("object_list")
return context
doc: https://docs.djangoproject.com/en/2.2/ref/class-based-views/generic-display/#listview
Upvotes: 2