将数据添加到方法变量中

时间:2016-06-24 12:17:47

标签: django django-templates django-views

我的问题有点超出我的知识范围。简单来说,有没有办法将数据添加到方法变量?

例如,假设我有一个包含大量文章的网站。每篇文章可能由不同的作者撰写。 “articles”和“user”位于不同的表中,但通过“user_id”链接。

我可以在HTML(big ol list)中轻松地显示文章。但我不知道如何将用户名或用户名/姓附加到其中。我知道我需要以某种方式“更新”方法变量才能使其工作。

models.py

class Articles(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    title = models.CharField(max_length=150, default='')
    description = models.CharField(max_length=5000, default='')

views.py

def index(request):
    context = {}
    articles = Articles.objects.all
    context = {'articles': articles}
    return render(request, 'projsapp/index.html', context)

的index.html

<tbody>
    {% for piece in articles %}
        <h1>{{ piece.title }}</h1>
        <h3>{{ piece.description }}</h3>
        <h6>Article by {{ piece.username }}</h6>
    {% endfor %}
</tbody>

这种情况下的方法变量是“文章”。显然“piece.username”不起作用,所以如何附加它?谢谢!

1 个答案:

答案 0 :(得分:1)

每篇文章(或piece)都没有username属性。相反,每篇文章都有一个user,而后者又有一个username属性。因此,您需要获取文章user,并获取user username

{{ piece.user.username }}