Django在一个温度下显示多个型号

2024-05-29 10:06:37 发布

您现在位置:Python中文网/ 问答频道 /正文

如何对局部视图执行相同的操作?在

在视图.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

简介_视图.html在

^{pr2}$

我只需要将列表中的第一个显示为详细信息视图。有什么办法吗?在


Tags: pyself视图datagethtmlcontext局部
2条回答

在queryset上使用first() method

视图.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

简介_视图.html

^{pr2}$

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

您已经给迭代变量指定了与迭代器相同的名称,只是使它们不同而已

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

相关问题 更多 >

    热门问题