我正在寻找一种方法来返回 True 或一个字符串,然后使用该信息来显示或不显示某些内容。这是我的代码:
def time_remaining(self):
timer = self.timer
now = datetime.datetime.utcnow().replace(tzinfo=utc)
if timer < now:
return True
else:
#Returns a timedelta in string
return game_logic.timedelta_format(timer - now)
然后我使用:
if time_remaining():
possible = True
else:
possible = False
return render(request, 'training.html',{'possible': possible})
最后在我的模板中:
{% if possible %}
<some html>
{% else %}
<different html>
{% endif %}
即使 time_remaining 返回字符串而不是 True,我总是以某种方式结束
我该如何解决这个问题?
请您参考如下方法:
在 Python 中,非空字符串也计算为 True:
>>> bool('foo')
True
>>> bool('')
False
因此无论您的 time_remaining 函数返回什么,它在您的 if 语句中总是被评估为 True。
你可能想使用类似的东西:
time_remaining() == True
或者如果没有剩余时间,甚至可以让 time_remaining 返回 False 或 None(特别是如果您只打算使用输出time_remaining 在你的 if 语句中)。
