python - Django form -Fill in duration field when 2 DateField were selected -


i have form employee apply leaves, how can make selecting start date , end date field in form calculate duration in days. how can calculation in view.py?

any appreciated

below code :

model.py :

class leave(models.model):     employee = models.foreignkey(employee, on_delete=models.cascade, related_name='+')     start_date = models.datefield()     end_date = models.datefield()     duration = models.floatfield() 

form.py :

class leavesdetailform(forms.modelform):     class meta:         model = leave         fields = ('employee','start_date', 'end_date', 'duration',)          widgets = {'start_date': forms.dateinput(attrs={'type': 'date'}),                    'end_date': forms.dateinput(attrs={'type': 'date'}),                    'employee': forms.hiddeninput()} 

view.py :

def my_leaves_view(request):     form = leavesdetailform(request.post or none)     leaves_log = leave.objects.all().filter(employee=request.user.profile.employee.id)     annual_field in leaves_log:         annual_duration = annual_field.end_date - annual_field.start_date     print(annual_duration)     if form.is_valid():         inst = form.save(commit=false)         inst.save()         return httpresponseredirect('my_leaves_content.html')     context = {'form': form}     return render(request, 'hrm/my_leaves/my_leaves_content.html', context) 

a subtraction of 2 dates gives datetime.timedelta, can use days attribute:

(annual_field.end_date - annual_field.start_date).days

for example:

>>> datetime import date >>> date(year=2017, month=10, day=10) - date(year=2017, month=10, day=1) datetime.timedelta(9) >>> (date(year=2017, month=10, day=10) - date(year=2017, month=10, day=1)).days 9 

if want save days:

def my_leaves_view(request):     # ...     form = leavesdetailform(request.post)     if form.is_valid():         inst = form.save(commit=false)         inst.duration = (inst.end_date - inst.start_date).days         inst.save()         return httpresponseredirect('my_leaves_content.html')     # ... 

Comments

Popular posts from this blog

android - InAppBilling registering BroadcastReceiver in AndroidManifest -

python Tkinter Capturing keyboard events save as one single string -

sql server - Why does Linq-to-SQL add unnecessary COUNT()? -