Question

Model:

class Subject (models.Model):
    name = models.CharField(max_length=50)
    day = models.CharField(max_length=50)

In my sql table i have more than 50 users and everyone have assigned one day of a week (ie. user1 -> MON, user2 -> MON, user3 -> WED ...)

In template below I want to display table with Days and Subject names, but I want to display day names only once as a head of a users group.

<table>
<tr class="head"><th>SUBJECTS</th></tr>

{% for field in subjects_all %}
    {% if forloop.first %}
    <tr class="head"><td colspan=5 align="center">MONDAY</td></tr>
    {% endif %}

    {% if field.day == "MON"  %}
    <tr><td>{{ field.name }}</td></tr>
    {% endif %}

    {% if ... } # <- ???
    <tr class="head"><td colspan=5 align="center">TUESDAY</td></tr>
    {% endif %}

    {% if field.day == "TUE"  %}

    <tr><td>{{ field.name }}</td></tr>

    {% endif %}

    (...)

{% endfor %}

</table>

In example belowe I know I can display Monday only once using forloop.first, but how can I display rest of days only once at top of a group of users ? If I do normal 'if' , TUESDAY will display on top of every single user found in database and that's not what I want.

EDIT: And I want to avoid copying whole for loop 7 times for every day in a week

Was it helpful?

Solution

You probably want the ifchanged template tag.

Alternatively, you could use regroup to group the items into days.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top