pynovice
pynovice

Reputation: 7752

Custom template tag to get a remaining days in Django

I have a model like this:

class WeddingDate(models.Model):
    user = models.ForeignKey(User)
    date = models.DateField(help_text="Date should be in 1991-07-22 format!")

User enters the date of their wedding. And, I find the remaining days for their wedding and show in base.html. I am trying to create a custom template tag for it.

I have create a directory called templatetags and created a file called remainingdays.py

from models import WeddingDate
from django import template
from datetime import date

register = template.Library()

def get_remaining_day(user):
    date = WeddingDate.objects.get(pk=user)
    current_date = date.today()
    days = date.date - current_date
    return days.days 

Now, how do I displays it in template like {% get_remaining_day %}

Upvotes: 1

Views: 756

Answers (1)

Timmy O'Mahony
Timmy O'Mahony

Reputation: 53998

First, you need to choose what type of template tag you are writing. It is probably easiest to use an assignment tag. You also need to register the template tag so that it's available in your template:

Either below your function:

def get_remaining_day(user):
    ...
register.assignment_tag('get_remaining_day', get_remaining_day)

or as a decorator:

@register.assignment_tag(name='get_remaining_day')
def get_remaining_day(user):
    ...

Now you can call it from your template as:

{% get_remaining_day as day %}
{{ day }}

Upvotes: 2

Related Questions