我研究了如何将日期时间对象传递到我的模板,但它们似乎都不起作用。这是我的观点的代码:
class LeadListView(LoginRequiredMixin, generic.ListView):
# some other code
today_date = datetime.date.today()
def get_context_data(self, **kwargs):
context = super(LeadListView, self).get_context_data(**kwargs)
context['today_date'] = self.today_date
return context
但是,当我尝试在模板中使用 today_date
时,它不起作用。我正在尝试使用 today_date
,以便我可以在 if 语句中使用它来查看今天的日期是否在其他两个日期时间变量之间。非常感谢!
有关 django 模板外观的一些附加信息:
{% if lead.class_start_date <= today_date and lead.class_end_date >= today_date %}
{% endif %}
这里,class_start_date
和 class_end_date
只是 Lead 模型的一部分。
这是完整 ListView :
class LeadListView(LoginRequiredMixin, generic.ListView):
tempalte_name = "leads/lead_list.html"
context_object_name = "leads"
def get_queryset(self):
user = self.request.user
# initial queryset of leads for the entire organisation
if user.is_organisor:
queryset = Lead.objects.filter(
organisation=user.userprofile,
agent__isnull=False
)
else:
queryset = Lead.objects.filter(
organisation=user.agent.organisation,
agent__isnull=False
)
#filter for the agent that is logged in
queryset = queryset.filter(agent__user=user)
return queryset
最佳答案
您不需要将其传递给上下文。 Django 已经有一个 {% now … %}
template tag [Django-doc] .
因此,您可以使用以下方式呈现此内容:
{% <b>now 'DATE_FORMAT'</b> %}
如果您计划过滤,但是在当天,您应该在 View 中进行过滤,因为这将在数据库级别进行过滤,这样效率更高:
from django.utils.timezone import now
class LeadListView(LoginRequiredMixin, generic.ListView):
model = Lead
def get_queryset(self, *args, **kwargs):
today = now().date()
return super().get_queryset(*args, **kwargs).<b>filter(</b>
class_start_date__lte=today,
class_end_date__gte=today
<b>)</b>
关于python - 如何将今天的日期添加到 django 模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66882721/