Hello everybody.
Title says it all: one of my models contains a DateTimeField, but I would like to render only the Date part of it to a template. If I use {{ book.finished_date }} it displays the whole DateTimeField string.
I think I know of a way of doing this, namely using datetime.date() to extract the date from the DateTimeField, and then passing the date in as a separate context key:value pair in the View. I suspect there’s a simpler way of doing this though. If anybody has any input on this topic it would be much appreciated.
(Is it possible in the Model class to somehow override the string display of that model field?)
The model:
class Book(models.Model):
title = models.CharField(max_length=75)
author = models.CharField(max_length=75)
book_owner = models.ForeignKey(get_user_model(), on_delete=models.CASCADE, related_name="books")
order = models.PositiveSmallIntegerField()
cover = models.ImageField(upload_to="covers/", blank=True, null=True)
# this are new
finished = models.BooleanField(default=False)
finished_date = models.DateTimeField(blank=True, null=True)
review = models.TextField(blank=True, null=True)
class Meta:
ordering = ['order']
def __str__(self):
return self.title
The template:
<div class="p-2" style="width: 95%; margin: auto;">
<h1 class="my-4 text-start">My completed books</h1>
<p class="lead">Lorem ipsum dolor sit amet, consectetur adipiscing elit,
sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.
Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.
Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
<table class="table">
<thead>
<tr>
<th scope="col">Title</th>
<th scope="col">Author</th>
<th scope="col">Review</th>
<th scope="col">Date Finished</th>
</tr>
</thead>
<tbody>
{% for book in finished_book_list %}
<tr>
<td>{{book.title}}</td>
<td>{{book.author}}</td>
<td>{{book.review}}</td>
<td>{{book.finished_date}}</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>