如何在模板中呈现表格

时间:2019-05-22 10:49:43

标签: python django django-models django-views

模型


timetable_choices =(
    ('Monday','Monday'),
    ('Tuesday','Tuesday'),
    ('Wednesday','Wednesday'),
    ('Thursday','Thursday'),
    ('Friday','Friday'),
    ('Saturday','Saturday'),
)


class Timetable(models.Model):
    day = models.ForeignKey('Day',on_delete=models.CASCADE,blank=True,null=True)
    start = models.IntegerField()
    end = models.IntegerField()
    subject = models.CharField(max_length=12)

class Day(models.Model):
    day = models.CharField(max_length=9, choices=timetable_choices)

我已经填充了Day表和Timetable表。

观看次数


class Timetabletemplate(TemplateView):
    template_name = 'timetable.html'

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['timetable'] = Timetable.objects.all()
        context['monday'] = Timetable.objects.filter(day="Monday")
        return context

模板

<table style="width:100%">
  <tr>
    <th></th>
    <th>1</th>
  </tr>
  <tr>
    <td>Monday</td>

    {% for item in monday %}
<td>{{item.subject}}</td>
      {% endfor %}

  </tr>
</table>

我想做的是渲染单元格中的主题。我有n个主题,主题的数量取决于用户添加了多少个主题。我希望第一行中的day = Monday时的主题,而星期一以下各行中的day = Tuesday,wednesday时的主题相似。

尝试此代码时出现错误 invalid literal for int() with base 10: 'Monday'

1 个答案:

答案 0 :(得分:3)

context['monday'] = Timetable.objects.filter(day__day="Monday")

在使用ForeignKeyDay模型时,日期另存为pk,而不是选项名称