Python Django在单个模板中显示多个模型
如何对详图视图执行相同的操作 views.pyPython Django在单个模板中显示多个模型,python,django,django-templates,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_
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 %}
{{user.username}
{配置文件%中的配置文件为%1}
{{profile.full_name}
{%endfor%}
我只需要将列表中的第一个显示为详细视图。有方法吗?您已经给迭代变量起了与迭代器相同的名称,只是让它们不同而已
{% for prof in profile %}
<p>{{ prof.full_name }}</p>
{% endfor %}
{%用于prof in profile%}
{{教授全名}
{%endfor%}
在queryset上使用
视图.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\u view.html
<h1>{{ user.username }}</h1>
<p>{{ profile.full_name }}</p>
{{user.username}
{{profile.full_name}
您还可以用来更改查询集的顺序。您已经为迭代变量指定了与迭代器相同的名称,只是让它们有所不同而已我是初学者。。你能举个例子吗?我不是在显示列表。这是一个单一的项目。for循环仅用于列表视图,对吗?当前,我正在添加slice以仅获取第一项。您已经将
profile
添加到您的上下文数据中,for循环用于iterable数据。