如何在Django模板中的两个时间点之间依次列出日期?

时间:2019-05-11 17:00:54

标签: django

我想自动生成时间表。我创建了一个模型,如下所示:

class Timetable(models.Model):
    user = models.OneToOneField(User,on_delete=models.SET_NULL, null=True, blank=True)
    fromDate = models.DateField(blank = False, null = False)
    toDate = models.DateField(blank = False, null = False)
    heading = models.CharField(max_length =50,blank=True, null = True)

我想列出fromDate和toDate之间的日期列表,并在模板上显示该列表。

2 个答案:

答案 0 :(得分:0)

是的,可以将两个日期转换为它们的 ordinal (自1月1日起的天数),然后使用range(..)并将其映射回一个日期,例如:

from datetime import date

def date_range(from_date, to_date):
    return map(date.fromordinal, range(from_date.toordinal(), to_date.toordinal()+1))

例如,我们可以这样称呼:

>>> list(date_range(date(2019, 2, 3), date(2019, 2, 9)))
[datetime.date(2019, 2, 3), datetime.date(2019, 2, 4), datetime.date(2019, 2, 5), datetime.date(2019, 2, 6), datetime.date(2019, 2, 7), datetime.date(2019, 2, 8), datetime.date(2019, 2, 9)]

例如,我们可以在视图中使用它,然后像这样传递它:

from django.shortcuts import get_object_or_404, render

def some_view(request, pk):
    obj = get_object_or_404(Timetable, pk=pk)
    context = {
        'obj': obj,
        'date_range': date_range(obj.fromDate, obj.toDate)
    }
    return render(request, 'template.html', context)

并将其呈现在模板中,例如:

{% for curdate in date_range %}
    {{ curdate }}
{% endrange %}

答案 1 :(得分:0)

# in models.py

class Timetable(models.Model):
    user = models.OneToOneField(User,on_delete=models.SET_NULL, null=True, blank=True)
    fromDate = models.DateField(blank = False, null = False)
    toDate = models.DateField(blank = False, null = False)
    heading = models.CharField(max_length =50,blank=True, null = True)
    def date_range(self):
        return list(map(date.fromordinal, range(self.fromDate.toordinal(),              self.toDate.toordinal()+1)))

# in views.py

def fun(request):
    template_name = 'x'
    timetables = Timetable.objects.filter(user = request.user)
    context = {'timetables':timetables}
    return render(request, template_name, context)

# in template

{% for table in timetables %}
<div class="table">
  {% for i in table.date_range %}
  <li>{{ i.month }}/ {{ i.day }}</li>
  {% endfor %}
</div>
{% endfor %}