Issue
I'm trying to show the date-created tasks in my list in HTML.
class Task(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True)
title = models.CharField(max_length=200)
description = models.TextField(max_length=1000, blank=True, null=True)
complete = models.BooleanField(default=False)
created = models.DateTimeField(auto_now_add=True)
And this is my HTML in Django
<div class="task-items wrapper">
{% for task in tasks %}
<div class="task-wrapper">
{% if task.complete %}
<div class="task-title">
<div class="task-complete-icon"></div>
<i><s><a class="task" href="{% url 'update-task' task.id %}">{{task}}</a></s></i>
<br></br>
</div>
<a class="delete-link" href="{% url 'delete-task' task.id %}"><i class="fa-solid fa-delete-left"></i></a>
{% else %}
<div class="task-title">
<div class="task-incomplete-icon"></div>
<a href="{% url 'update-task' task.id %}">{{task}}</a>
</div>
<a class="delete-link" href="{% url 'delete-task' task.id %}"><i class="fa-solid fa-delete-left"></i></a>
{% endif %}
</div>
<div class="emptylist">
{% empty %}
<h3 style="text-align: center; line-height: 3;">No task in list! Let's create your task</h3>
</div>
{% endfor %}
</div>
For example, for each task I create, it must show the title with the date created, and doesn't matter if it is completeđ or incomplete. I just can show the title and how do I do that show the date?
Solution
You could use DateField()django-doc directly. But if you have defined DateTimeField so you can use @property decorator and show date in the format like 1-7-2022 as you shown in the picture.
Create @property in your Task model like this:
class Task(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True)
title = models.CharField(max_length=200)
description = models.TextField(max_length=1000, blank=True, null=True)
complete = models.BooleanField(default=False)
created = models.DateTimeField(auto_now_add=True)
@property
def get_only_date(self):
date_object = self.created
year = date_object.year
month = date_object.month
day = date_object.day
return f"{day}-{month}-{year}"
Then, use anywhere in your template file as property in loop:
{% for task in tasks %}
{{task.get_only_date}}
{% endfor %}
Answered By - Sunderam Dubey
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.