python - 如何将今天的日期添加到 django 模板

标签 python django datetime variables django-templates

我研究了如何将日期时间对象传递到我的模板,但它们似乎都不起作用。这是我的观点的代码:

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_dateclass_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/

相关文章:

python - 如何在Python中根据3个预定义列表(f'{list1}_{list2}_{lists} ')动态生成变量名称?

django - 从麦克风录制音频并另存为.wav django Web应用

html - 嵌入不适用于 HTTPS 站点上的 django-embed-video

javascript - 在 codeigniter 中查找数据库中的两个日期时间差异

python - 值错误 : time data does not match format when parsing a date

python - Pandas 计算日期时间差异,但针对每个用户

python - 通过 python 强化 sshd_config

python - 在数组的 numpy 数组中找到 n 个最小的项目

python - 使用 Python 中的 xml 子对象、ElementTree

django - 使用非模型字段序列化 Django RawQuerySet 的推荐方法