[英]Django template doesn't render models as I would expect
So I have this Lecture class. 所以我有这堂课。 Now for this class, I have 2 choices: "Classes" and "Seminars", and I want that each time I add a lecture to either one, the template will shows firstly the choice and then all the lectures.
现在,在本课程中,我有2个选择:“班级”和“研讨会”,并且我希望每次向任一课程添加一个讲座时,模板将首先显示该选择,然后显示所有讲座。 Example: Classes will have Lecture1, Lecture2, Lecture3 etc. Problem is that right now when I iterate, choice shows each time, for every lecture and I want each choice to show only ONCE.
示例:班级将具有Lecture1,Lecture2,Lecture3等。问题是,现在当我进行迭代时,每次选择都会显示一次,对于每个讲座,我都希望每个选择只显示一次。
class Lecture(models.Model):
course = models.ForeignKey('Course', on_delete=models.CASCADE, default='', related_name='lectures')
lecture_category = models.IntegerField(choices=((0, "Classes "),
(1, "Seminars"),
))
lecture_title = models.CharField(max_length=100)
content = models.TextField()
link = models.URLField(blank=True)
file = models.FileField(upload_to='documents', blank=True)
def __str__(self):
return self.lecture_title
<ul>
{% for c in lectures %}
<b>{{ c.get_lecture_category_display }}</b>
<p>.......................</p>
<li>{{ c.lecture_title }}</li>
<li>{{ c.content }}</li>
{% if c.link %}
<li>{{ c.link }}</li>
{% if c.file %}
<li><a href='{{ MEDIA_URL }}{{ c.file.url }}'>download</a></li>
{% endif %}
{% endif %}
{% endfor %}
<hr/>
</ul>
There is a template tag called regroup that you can use for this. 您可以使用一个名为regroup的模板标签。 See the regroup section at https://docs.djangoproject.com/en/2.0/ref/templates/builtins/
请参阅https://docs.djangoproject.com/en/2.0/ref/templates/builtins/
{% regroup lectures by lecture_category as category_list %}
<ul>
{% for category in category_list %}
<li>{{ category.grouper }}
<ul>
{% for c in category.list %}
<li>{{ c.lecture_title }}</li>
<li>{{ c.content }}</li>
...etc
{% endfor %}
</ul>
</li>
{% endfor %}
</ul>
Edit: As Daniel Rosemen pointed out, you will also have to sort the query by the field you want to regroup on in your view. 编辑:正如Daniel Rosemen指出的那样,您还必须按要在视图中重新组合的字段对查询进行排序。 In this case you would have to order lectures by lecture_category.
在这种情况下,您将必须按“ student_category”订购讲座。 The above method will not work otherwise.
否则,上述方法将无效。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.