如何在Django中找到开始日期和间隔的结束日期?

时间:2017-06-23 16:00:30

标签: python django date

这与我在此问的问题有关:My form in Python Django is not submitting

以下是相关代码

#choices.py

INTERVAL_CHOICES = (('one_day', '1 Day'), ('two_days', '2 Days'), ('three_days', '3 Days'), ('four_days', '4 Days'), ('five_days', '5 Days'), ('six_days', '6 Days'), ('one-week', '1 Week'),
                ('two_weeks', '2 Weeks'), ('three_weeks', '3 Weeks'), ('four_weeks', '4 Weeks'), ('five_weeks', '5 Weeks'), ('six_weeks', '6 Weeks'), ('eight_weeks', '8 Weeks'), ('twelve_weeks', '12 Weeks')
                )

#models.py

class Schedules(models.Model):
    start_date = models.DateField(auto_now=False, auto_now_add=False, default=datetime.date.today)
    interval = models.CharField(max_length=128, choices=INTERVAL_CHOICES, default='one_day')

#views.py

def schedule_List(request):
    schedule_list = Schedules.objects.all()
    context_dict = {'schedules': schedule_list}
    return render(request, "schedule/schedule_list.html", context_dict)

我需要从开始日期和间隔中找到结束日期,然后才能将结束日期放入模板中。我假设我需要以某种方式将区间选择中元组的第二部分转换为整数,然后将任何具有“周”的选项相乘。或者'周'在他们中7,然后以某种方式将其添加到开始日期。有没有人对此有所了解,以及如何将结束日期发布到模板中?感谢。

编辑:我应该提一下,我使用表单将数据放入数据库。以下是相关代码:

#forms.py
class ScheduleForm(forms.ModelForm):
    start_date = forms.DateField(initial=datetime.date.today, label="Start Date")
    interval = forms.ChoiceField(choices=INTERVAL_CHOICES, initial='one_day', label="Interval")
    class Meta:
        model = Schedules
        fields = ('start_date', 'interval',)

#views.py
def start_One_Schedule(request):
    form = ScheduleForm()
    if request.method == 'POST':
        form = ScheduleForm(request.POST)

    if form.is_valid():
        form.save(commit=True)
        return render(request, 'schedule/schedule.html', {})
    else:
        print(form.errors)

    return render(request, 'schedule/start_one_schedule.html', {'form': form})

2 个答案:

答案 0 :(得分:1)

答案 1 :(得分:0)

它认为最好的方法是将其存储为有人建议的持续时间,然后在模板中将其存储

{% for schedule in schedules %}
   <p>End Date: {{ schedule.start_date|add:schedule.interval }}</p>
{% endfor %} 

(免责声明,我从未尝试过)。当然,如果您不想更改模型,则必须循环查看在视图中查询的对象。以下是它的样子。

import datetime

def parse_interval(interval):
    interval_dict = {'one_day':{'days':1}, 'two_days':{'days':2}, 'three_days':{'days':3}, 'four_days':{'days':5}, 
    # . . . .
    'twelve_weeks': {'weeks':12}}
    return interval_dict[interval]    

def schedule_list(request):
    schedule_list, new_sched_list = Schedule.objects.all(), []
    for sched in schedule_list:
        sched.end_date = sched.start_date + datetime.timedelta(**parse_interval(sched.interval))
        new_sched_list.append(sched)
    context_dict = {'schedules': new_sched_list}
    return render(request, "schedule/schedule_list.html", context_dict)

您可以像访问任何其他字段一样访问模板中的end_date