【问题标题】:How can I contain more than 2 models in one template?如何在一个模板中包含 2 个以上的模型?
【发布时间】:2017-10-16 07:52:47
【问题描述】:

我是自己研究 Django 的学生。 我简单介绍一下我的项目。

  1. 获取棒球运动员的记录
  2. 在我的网站上显示

我的项目完成在冰雹距离之内。但我有一个问题。 这是我的观点。py

from django.shortcuts import get_object_or_404, render
from displayer.models import Profile, SeasonRecord

def index(request):
    profile_list = Profile.objects.all().order_by('-no')[:5]
    context = {'profile_list': profile_list}

    return render(request, 'displayer/index.html', context)

def data(request, profile_id):
    profile = get_object_or_404(Profile, pk=profile_id)
    season = SeasonRecord.objects.all().order_by('-no')[:5]
    context = {'profile': profile, 'season':season}

    return render(request, 'displayer/data.html', context)

我想在视图函数(数据)中包含 2 个模型(Profile、SeasonRecord),并且我将在这个视图函数中包含更多模型。但它只包含 Profile 模型。

这是 urls.py

from django.conf.urls import url 
from django.contrib import admin
from displayer import views

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^displayer/$', views.index, name='index'),
    url(r'^displayer/(?P<profile_id>\d+)/$', views.data, name='data'),
]

这是data.html

<h1>{{ profile.number }}</h1>
<h1>{{ profile.name }}</h1>

<table align="left" border="1">
<tr>
    <td>position</td>
    <td>debut</td>
    <td>born</td>
    <td>body</td>
</tr>
<tr>
    <td>{{ profile.position }}</td>
    <td>{{ profile.debut }}</td>
    <td>{{ profile.born }}</td>
    <td>{{ profile.body }}</td>
</tr>
</table>

<br/><br/><br/><br/><br/>

<table align="left" border="1">
    <tr>
        <td>avg</td>
        <td>rbi</td>
    </tr>
    <tr>
        <td>{{ season.avg }}</td>
        <td>{{ season.rbi }}</td>
    </tr>
</table>

帮帮我.. 我该怎么办?

我使用的是 django 版本 1.10.5,python 版本 3.5.2

【问题讨论】:

  • season 返回多个对象,因此您需要在模板中对其进行循环。 Profile 返回一个对象,因此您无需遍历它。我认为这就是你犯错的地方。

标签: python django templates view model


【解决方案1】:

你需要使用django模板循环

<table align="left" border="1">
    <tr>
        <td>avg</td>
        <td>rbi</td>
    </tr>
    {% for season in seasons %}
      <tr>
        <td>{{ season.avg }}</td>
        <td>{{ season.rbi }}</td>
      </tr>
    {% endfor %}
</table>

这是必须的

context = {'profile': profile, 'season':seasons}

当然,这些可以是您想要的任何变量名称。我正在按照习俗多元化季节

【讨论】:

  • 我在您的帮助下完成了项目。谢谢:)
  • 很高兴能帮上忙。
猜你喜欢
  • 1970-01-01
  • 2012-08-15
  • 1970-01-01
  • 2021-06-23
  • 1970-01-01
  • 1970-01-01
  • 2015-03-09
  • 1970-01-01
  • 2016-04-10
相关资源
最近更新 更多