user298519 user298519 - 2 months ago 8
Python Question

Django: How to display author of query of posts?

I'm trying to make individual pages for each author showing their name and posts. I can't seem to get the username displayed.

views.py

class UserProfileView(generic.ListView):
template_name = 'howl/user-profile.html'
context_object_name = 'user_howls'

def get_queryset(self):
author = self.request.user
u = User.objects.get(username=author)
return Howl.objects.filter(author=u)


models.py

class Howl(models.Model):
author = models.ForeignKey(User, null=True)
content = models.CharField(max_length=150)


Here is where I'm stuck.

user-profile.html

{% extends 'howl/base.html' %}

{% block content %}

<h1>User: {{user_howl.author}}</h1>

{% for user_howl in user_howls %}
<ul>
<li>{{user_howl.content}}</li>
</ul>
{% endfor %}

{% endblock %}


The content is displayed just fine, but the heading just says "User: ", how do I give it a context without using a for loop?
I've tried:

{% for author in user_howls.author %}
<h1>User: {{author}}</h1>
{% endfor %}


and

{% if user_howls.author %}
<h1>User: {{user_howl.author}}</h1>
{% endif %}


Still the same outcome, displaying "User: "

Answer

Since your queryset is based on the posts belonging to the current user, you can shortcut all of this and just show the user directly:

User: {{ user }}
Comments