user298519
user298519

Reputation: 1190

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: "

Upvotes: 0

Views: 1351

Answers (2)

Daniel Roseman
Daniel Roseman

Reputation: 599580

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 }}

Upvotes: 1

Sayse
Sayse

Reputation: 43300

user_howls is a queryset so it won't have an author attribute, you need to get the author of the iterated object

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

More to the point though, it doesn't make sense to start from a Howl list, when you are just returning the results for the user_profile, nor does it make sense to use a ListView. so instead, start from the user and then look up its howls

user_obj.howl_set.all()

Upvotes: 3

Related Questions