如何对细节视图进行相同的操作?
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 %}
我只需要在列表中显示第一个作为详细视图。任何方法?
答案 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更改查询集的顺序。