Difference between two date fields from Django form

How to find the difference between two date fields from django forms


class task_form(forms.ModelForm):

    start_date = forms.DateField(widget = forms.widgets.DateInput(attrs={'type': 'date'}), label = 'Start date', required = False)
    due_date = forms.DateField(widget = forms.widgets.DateInput(attrs={'type': 'date'}), label = 'End date',required = False)
    duration = forms.IntegerField(required = False, label = 'Duration', disabled = True) 


def edit_view(request):

    if request.method == "POST":
        form = task_form(request.POST)
        if task_edit_form.is_valid():
            temp = form.save(commit= False)
            temp.bfs_task_duration = temp.start_date - temp.due_date

But this doesn't work and I couldn't find any resources helping to find the differences between two date fields, Please help

Thanks in Advance

2 answers

  • answered 2019-04-15 06:14 ruddra

    temp.start_date - temp.due_date should return a timedelta object. If you want to store the days then do it like this:

    bfs_task_duration = temp.start_date - temp.due_date
    temp.bfs_task_duration = bfs_task_duration.days

  • answered 2019-04-15 06:16 im_shankarmahato

    try this, temp.bfs_task_duration = abs((temp.start_date - temp.due_date).days)