Right now, I have a few logs in my database and I want to display them by date in the Django template. How do I do it?
This is what my current system looks like..
This is how I want them to look.
JUNE 20, 2022
-------------
Nice songs! I'm listening to Massive Attack right now - 03:06 AM
JUNE 19, 2022
-------------
Just completed a sketch of the LOG IT! - 21:48 PM
I'm watching a movie right now. It's called Black Swan - 21:30 PM
Just had a pizza from Pagliacci! - 21:25 PM
models.py
class Logs(models.Model):
log = models.CharField(max_length=100)
created = models.DateTimeField(auto_now=False, auto_now_add=True)
views.py
class ViewLogs(ListView):
template_name = 'logs_list.html'
model = Logs
form_class = LogForm
def get_logs(self):
logs = Logs.objects.all().order_by('-created')
return logs
def get_form(self):
form = LogForm()
return form
def get_context_data(self, *args, **kwargs):
context = super().get_context_data(*args, **kwargs)
context['query'] = self.request.GET.get('q', None)
form = self.get_form()
logs = self.get_logs()
context['form'] = form
context['logs'] = logs
return context
logs_list.html
{% for log in logs %}
<div >
<div >
<p style="color:black;max-width:1000px;"> {{ log.log | safe}} </p>
<small style="color:gray;" > {{ log.created | date:"F d, o - H:i A" | upper }} </small>
</div>
</div>
{% endfor %}
CodePudding user response:
Regrouping is your friend in this case. It allows you to clump things by common attributes, including attributes that have been filtered by template filters! See the docs for more. Something like:
{% regroup logs by created|date:"F d, Y"|upper as log_days %}
{% for day in log_days %}
<div >
<h2 >{{ day.grouper }}</h2>
{% for log in day.list %}
<p>{{ log.log|safe }} - {{ log.created|date:" H:i A"|upper }}<p>
{% endfor %}
</div>
{% endfor %}