Reputation:
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. 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.
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>
Upvotes: 0
Views: 42
Reputation: 966
There is a template tag called regroup that you can use for this. See the regroup section at 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. In this case you would have to order lectures by lecture_category. The above method will not work otherwise.
Upvotes: 2