如果时间不是09:00到17:00之间的工作日,我想在模板(base.html)中隐藏一个块。
我在想(非常简化):
{% if now is 09:00 and 17:00 on weekdays %}
#Show callback form
{% else %}
#We do not answer the phone before 09:00 and after 17:00
{% endif %}
有可能吗?
答案 0 :(得分:1)
我建议您在view.py
import datetime
# In view
now = datetime.datetime.now()
call_us_now = False
if 9 < now.hour < 17:
call_us_now = True
# Send 'call_us_now' to context
{# In template #}
{% if call_us_now %}
{# Show callback form #}
{% else %}
{# We do not answer the phone before 09:00 and after 17:00 #}
{% endif %]
答案 1 :(得分:1)
我想在我的base.html上使用这个代码,所以可能有点困难 在每个视图上实现你的代码?
撰写自定义template context processor
。您可以将此作为起点:
from datetime import datetime, time
from django.conf import settings
def calling_flag(request):
""" Sets the flag in the template if the current time is between CALL_HOURS """
if settings.CALL_HOURS:
now = datetime.now().time()
start_time,end_time = settings.CALL_HOURS
start_time = time(start_time[:2],start_time[-2:])
end_time = time(end_time[:2],end_time[-2:])
return {'IN_TIME': start_time <= now <= end_time}
将其保存在应用内的文件中。假设该应用程序名为feedback
,您将上述代码放在custom_template_flags.py
目录中名为feedback
的文件中。下一步,将其添加到settings.py
:
TEMPLATE_CONTEXT_PROCESSORS = (
# -- your other context processors
'feedback.custom_template_flags.calling_flag',
)
最后,再次在settings.py
:
CALL_HOURS = ('0900','1700')
现在,所有模板都会有{{ IN_TIME }}
True
或False
。