1

我有一个这样的模型:

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

用户输入他们的婚礼日期。而且,我找到了他们婚礼的剩余日子,并在base.html. 我正在尝试为它创建一个自定义模板标签。

我创建了一个名为 templatetags 的目录并创建了一个名为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 

现在,我如何在模板中显示它{% get_remaining_day %}

4

1 回答 1

2

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 }}
于 2013-10-02T07:58:46.580 回答