0

models.py

from django.db import models

class Leave(models.Model):
    ...
    from_date = models.DateField()
    to_date = models.DateField()

    def __str__(self):
        return self.name

The above are the two date fields which are defined in my models.py.

views.py

from django.shortcuts import render, render_to_response
from .forms import LeaveRequestForm
from django.shortcuts import 
from .models import Leave
...
def get_days(request):
    data = Leave.objects.all()
    for x in data :
        if x.employee_ID == request.user.username:
            d1 = x.from_date
            d2 = x.to_date
            days = d2 - d1
    return render(request,"status.html", days)

The above code is my trial on getting the number of days.

Here, my model is Leave and my form is LeaveRequestForm. In my HTML file to get the number of days I use {{ from_date|timesince:to_date }}, this works but i want to deduct this number of days from a number.

base : I'm working on a leave-management project. If a user asks a leave for 5days and he is eligible for 10days. His balance leaves should be equal to 5.

How do I achieve this with the views?

bhanuprakash
  • 149
  • 3
  • 16
  • I answered a similar question here, [implementation of **`TIMESTAMPDIFF`**](https://stackoverflow.com/questions/51790498/how-to-implement-timestampdiff-of-mysql-in-django) – JPG Aug 28 '18 at 06:02
  • also this, [difference in days- Django](https://stackoverflow.com/a/51778823/8283848) – JPG Aug 28 '18 at 06:03
  • @JPG I'm not using MYSQL btw, I want a view not a model entry so that my db in dbsqlite3 doesn't effect and i can use it in a template. – bhanuprakash Aug 28 '18 at 06:05
  • @MD.KhairulBasar I use `{{ from_date|timesince:to_date }}` to get number of days, but I need to subtract this from a number. This isn't working – bhanuprakash Aug 28 '18 at 06:13
  • @Jose So, you may use a template variable. Or you can also use a model method. Here's the way to use a template variable [https://stackoverflow.com/a/1070414/3968623](here). – MD. Khairul Basar Aug 28 '18 at 06:16

2 Answers2

3

use property in model as

from django.db import models


class Leave(models.Model):
    from_date = models.DateField()
    to_date = models.DateField()

    def __str__(self):
        return self.name

    @property
    def date_diff(self):
        return (self.to_date - self.from_date).days

and in your template you could use it as {{ leave_object.date_diff }}

JPG
  • 82,442
  • 19
  • 127
  • 206
0

In your case, d2 - d1 is a timedelta object which has an integer property days.

So you need to write days = (d2 - d1).days in your python code, and you will get an int which you can subtract from whatever you need.

Mikhail Burshteyn
  • 4,762
  • 14
  • 27