Kristian Roebuck
Kristian Roebuck

Reputation: 3379

Django: Querying Multiple Foreign Keys

First off, I'm sure this is a simple question. I'm just getting started with Django and as all beginners do, I thought I'd build a simple blog.

I have a simple data model, a Post model that contains with a link to a user via a FK.

models.py

class Post(TimeStampedActivate):
    """
    A blog post
    """
    title = models.CharField(max_length=255)
    slug = models.SlugField()
    excerpt = models.TextField(blank=True)
    body = models.TextField()
    publish_at = models.DateTimeField(default=datetime.datetime.now())
    created = models.DateTimeField(auto_now_add=True)
    modified = models.DateTimeField(auto_now=True)
    active = models.BooleanField(default=False, help_text='Is the blog post active?')
    user = models.ForeignKey(User, related_name='post_user')

    def __unicode__(self):
        return self.title

I then want a page that lists all of the Posts alongside the username of the person who created the post. My current view looks like this:

views.py

def index(request):
    posts = Post.objects.filter(active=True)   
    user = User.objects.get(id=1)
    return render(request, 'blog/index.html', {'posts': posts, 'user': user})

My template At present this just displays the users name that matches an ID of 1.

{% for post in posts %}
    <h2><a href="{{ post.get_absolute_url }}">{{ post.title }}</a></h2>
    <p>{{ post.excerpt|truncatewords:30 }}</p>
    <p>Posted by {{ user.first_name }} {{ user.last_name }}</p>
{% endfor %}

How would I modify my views.py file to ensure I get the first and last name of the user responsible for the post?

Upvotes: 4

Views: 395

Answers (2)

dannyroa
dannyroa

Reputation: 5571

Use "post.user" in your template instead of just "user".

{{ post.user.first_name }} {{ post.user.last_name }}

"user" is the current logged-in user.

If you use RequestContext & added auth to your TEMPLATE_CONTEXT_PROCESSORS, user is equal to request.user. https://docs.djangoproject.com/en/dev/topics/auth/#authentication-data-in-templates

Upvotes: 1

Alp
Alp

Reputation: 29749

View:

def index(request):
    posts = Post.objects.filter(active=True)   
    return render(request, 'blog/index.html', {'posts': posts})

Template:

{% for post in posts %}
    <h2><a href="{{ post.get_absolute_url }}">{{ post.title }}</a></h2>
    <p>{{ post.excerpt|truncatewords:30 }}</p>
    <p>Posted by {{ post.user.first_name }} {{ post.user.last_name }}</p>
{% endfor %}

Upvotes: 3

Related Questions