I'm trying to display the difference between 2 giving dates on django, and i've managed to make it, but now i'm strugling to display only the days, without the time, is there any filter that i can use?
My html template:
<a href="{% url 'edit_contract' contract.id %}">
{% if contract.status == 'PN' %}
{{ today |sub:contract.starting_date }}
{% else %}
TODO
{% endif %}
</a>
My view:
@login_required
def contract_list(request):
contracts = Contract.objects.filter(user=request.user)
total_contracts_value = Contract.objects.filter(user=request.user).aggregate(sum=Sum('value'))['sum'] or 0
contracts_count = Contract.objects.filter(user=request.user).count()
today = date.today()
return render(request, 'list_contract.html', {'contracts': contracts,
'total_contracts_value': total_contracts_value,
'contracts_count': contracts_count, 'today':today})
CodePudding user response:
I think there are a few ways to do what you want here. I'll let you decide what you think works best for you.
- The
timesince
ortimeuntil
template formatting tags within Django may give you what you want immediately.
{{ today |timeuntil:contract.starting_date }}
https://docs.djangoproject.com/en/4.0/ref/templates/builtins/#timesince https://docs.djangoproject.com/en/4.0/ref/templates/builtins/#timeuntil
- Another option is to make use of the
datetime
module.
Here us an example showing the difference in days between a datetime object:
import datetime
now = datetime.datetime.now()
startingDate = now datetime.timedelta(days=7)
daysRemaining = (startingDate-now).days
print(daysRemaining) # INFO: prints '7'
I don't think this is what you want, but here is another example, using strftime
and timedelta
to get more specific formatting:
todaysDateFormatted = datetime.datetime.strftime(datetime.datetime.now() datetime.timedelta(days=1), "%d-%b-%Y")
CodePudding user response:
Days since start is a property of your contract, so you could create an actual property in the Contract model
from datetime import date
from django.db import models
class Contract(models.Model):
...
@property
def days_since_start(self):
today = date.today()
result = today - self.start_date
return result.days
then refer to the property in your template
{% if contract.status == 'PN' %}
{{ contract.days_since_start }}
{% else %}