Django在单个模板中显示多个模型

时间:2017-02-08 12:56:34

标签: python django django-templates

如何对细节视图进行相同的操作?

views.py

class ViewProfile(generic.DetailView):
    model = User
    slug_field = 'username'
    template_name = 'profile/profile_view.html'

    def get_context_data(self, **kwargs):
        ctx = super(ViewProfile, self).get_context_data(**kwargs)
        ctx['profile'] = Profile.objects.all()
        return ctx

profile_view.html

<h1>{{ user.username }}</h1>
{% for profile in profile %}
<p>{{ profile.full_name }}</p>
{% endfor %}

我只需要在列表中显示第一个作为详细视图。任何方法?

2 个答案:

答案 0 :(得分:0)

您已经给迭代变量赋予了与迭代器相同的名称,只是让它们不同

{% for prof in profile %}
<p>{{ prof.full_name }}</p>
{% endfor %}

答案 1 :(得分:0)

在queryset上使用first() method

<强> views.py

class ViewProfile(generic.DetailView):
    model = User
    slug_field = 'username'
    template_name = 'profile/profile_view.html'

    def get_context_data(self, **kwargs):
        ctx = super(ViewProfile, self).get_context_data(**kwargs)
        #  profile in your context will contain only the first profile
        ctx['profile'] = Profile.objects.all().first() 
        return ctx

<强> profile_view.html

<h1>{{ user.username }}</h1>
<p>{{ profile.full_name }}</p>

您还可以使用order_by() method更改查询集的顺序。