Django-在"if"语句中检查日期时间 [英] Django - Checking datetime in an 'if' statement
问题描述
我有一个非常有想象力的模型,叫做" model
",其中有一个字段" datefinish
";用户可以在此处以MM/DD/YYYY格式输入日期.在我的模板中,当所述模型的 datefinish
(日期)等于当前日期时,我需要显示一些文本.
I have a model very imaginatively called 'model
' which has a field 'datefinish
' in it; users can input a date here in the format MM/DD/YYYY. In my template I need some text displayed when said model has a datefinish
(date) that is equal to the current day.
HTML:
{% if model.datefinish == datetime.today %}
<h5>It ends today</h5>
{% else %}
<h5>It does not end today</h5>
{% endif %}
如何做到这一点?我正在使用Django 1.10 ...谢谢!
How might one achieve this? I'm using Django 1.10...thanks!
推荐答案
根据丹尼尔(Daniel)的建议,该模型选项是我的首选,因为当您加载该模型时,它始终可用
The model option as per Daniel's suggestion, which I prefer as then you have it always available whenever you load that model
在以下模式下:
@property
def is_today(self):
return self.datefinish == datetime.today().date()
这假定'datefinish'是一个DateField,而不是DateTimeField,对于DateTimeField,您可以 self.datefinish.date()== ...
this assumes that the 'datefinish' is a DateField, not a DateTimeField, for DateTimeField you would do self.datefinish.date() == ...
您还可以查看其是否在某个范围内,即
you can also see if its within a range, i.e.
return self.start_date <= datetime.today().date() <= self.end_date
如果模型中有两个日期.
if you have two dates in a model.
或创建一个模板标签,例如:
or create a template tag like:
@register.filter
def is_today(dt):
if isinstance(dt, datetime):
return dt.date() == datetime.today().date():
if isinstance(dt, date):
return dt == datetime.today().date():
然后您可以在模板中完成
then in the template you can do
{% if model.datetime_field|is_today %}
过滤器可以处理DateField和DateTimeField
The filter can handle DateField and DateTimeField
这篇关于Django-在"if"语句中检查日期时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!