I'm trying to group articles in each day, image blow will show you how it looks like now
I have 3 records that have their date on top right of them, but as you can see each one of them is separated, I want to show record on this date in one group and tomorrow if I added more records shows on that date group, my codes:
Models.py:
class Form(models.Model):
food_type = models.ForeignKey(FoodTypes, blank=False, null=True, on_delete=CASCADE)
calorie = models.CharField(max_length=50)
protein = models.ForeignKey(Protein, blank=False, null=True, on_delete=CASCADE)
carbohydrate = models.ForeignKey(Carbohydrate, blank=False, null=True, on_delete=CASCADE)
drinks = models.ForeignKey(Drinks, blank=False, null=True, on_delete=CASCADE)
fruits = models.CharField(max_length=50)
note = models.CharField(max_length=200, blank=True)
date = models.DateField(default=datetime.date.today)
views.py:
def requests(request):
lists = Form.objects.all().order_by('-date')
context = {
'lists': lists
}
return render(request, 'form/requests_list.html', context)
template file:
{% for lists in lists %}
<div class="req-list">
<h6>{{ lists.date }}</h6>
<table class="table table-striped">
<thead>
<tr>
<th scope="col">#</th>
<th scope="col">نوع غذا</th>
<th scope="col">کالری</th>
<th scope="col">پروتئین</th>
<th scope="col">کربوهیدرات</th>
<th scope="col">نوشیدنی</th>
<th scope="col">میوه</th>
<th scope="col">توضیحات</th>
</tr>
</thead>
<tbody>
<tr>
<th scope="row">{{ lists.id }}</th>
<td>{{ lists.food_type }}</td>
<td>{{ lists.calorie }}</td>
<td>@{{ lists.protein }}</td>
<td>@{{ lists.carbohydrate }}</td>
<td>@{{ lists.drinks }}</td>
<td>@{{ lists.fruits }}</td>
<td>@{{ lists.note }}</td>
</tr>
</tbody>
</table>
</div>
{% endfor %}
CodePudding user response:
You can try using the {% ifchanged %} tag as mentioned in this answer: https://stackoverflow.com/a/3986324/4151233
Following code is not tested:
{% for lists in lists %}
{% ifchanged lists.date %}
<div class="req-list">
<h6>{{ lists.date }}</h6>
<table class="table table-striped">
<thead>
<tr>
<th scope="col">#</th>
<th scope="col">نوع غذا</th>
<th scope="col">کالری</th>
<th scope="col">پروتئین</th>
<th scope="col">کربوهیدرات</th>
<th scope="col">نوشیدنی</th>
<th scope="col">میوه</th>
<th scope="col">توضیحات</th>
</tr>
</thead>
<tbody>
{% endifchanged %}
<tr>
<th scope="row">{{ lists.id }}</th>
<td>{{ lists.food_type }}</td>
<td>{{ lists.calorie }}</td>
<td>@{{ lists.protein }}</td>
<td>@{{ lists.carbohydrate }}</td>
<td>@{{ lists.drinks }}</td>
<td>@{{ lists.fruits }}</td>
<td>@{{ lists.note }}</td>
</tr>
{% ifchanged lists.date %}
</tbody>
</table>
</div>
{% endifchanged %}
{% endfor %}