Django 模板 - 是否有一种内置方法可以将当前日期作为“date"类型而不是“str"类型获取? [英] Django template - Is there a built-in way to get current date as type 'date' instead of type 'str'?

查看:25
本文介绍了Django 模板 - 是否有一种内置方法可以将当前日期作为“date"类型而不是“str"类型获取?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道我可以在 Django 模板中以 str 的形式获取当前日期(使用 模板标签now),像这样:

I know I can get the current date as a str in a Django template (using the template tag now), like this:

{% now "Y-m-d" as today_str %}
<p>{{ today_str }}</p>

但我不能将其用于比较:

But I cannot use that for comparissons:

{% now "Y-m-d" as today_str %}

{% for elem in object_list %}
    {% if elem.date < today_str %}        {# WRONG: this compares 'date' and 'str' #}
        <p>{{ elem.pk }} before today</p>
        {# do some other rendering #}
    {% endif %}
{% endfor %}

<小时>

可能的解决方案:


Possible solutions:

  1. 我知道我可以将上下文变量传递给模板,但在我看来它需要代码:

  1. I know I can pass a context variable to the template, but it requires code in my view:

# in my class-based-view in 'views.py'
def get_context_data(self, **kwargs):
    ctx = super().get_context_data(**kwargs)
    ctx['today'] = timezone.now()
    return ctx

  • 或者我可以创建一个自定义模板标签,但这需要更多的额外代码.

  • Or I can create a custom template tag, but that is even more additional code.

    正如你所看到的,我有解决我的问题的方法,但我想知道是否有一种内置方式来获取当前的date(或datetime) 在模板中?

    As you can see I have workarounds for my problem, but I would like to know if there is a buit-in way to get the current date (or datetime) in the template?

    推荐答案

    所以,我所有的搜索都没有找到一个简短的解决方案.问题的答案似乎是:不,没有内置方法可以将当前日期(或日期时间)作为模板中的变量.

    So, all my searching didn't yield a short solution. The answer to the question seems to be: no, there is no buit-in way to get the current date (or datetime) as a variable in the template.

    如果其他人正在搜索此主题,我将尝试总结我可以提出的以及其他用户建议的可能解决方法.

    In case others are searching for this topic, I'll try to give a summary of the possible workarounds that I can up with and that were suggested by other users.

    1. 我可以从我的视图中将上下文变量传递给模板.在看起来像这样的基于类的视图中(它甚至是 文档):

     # file 'my_app/views.py'
     from django.utils import timezone as tz
     from django.views.generic import ListView
    
     class MyView(ListView)
         ...
    
         def get_context_data(self, **kwargs):
             ctx = super().get_context_data(**kwargs)
    
             now = tz.now()
             ctx['now'] = now
             ctx['today'] = tz.localtime(now).date()
    
             return ctx
    

  • 我可以创建一个自定义的上下文处理器 将该变量加载到每个模板.在可能如下所示的基于类的视图中:

  • I could create a custom context processor that loads that variable to every template. In class-based views that could look like this:

     # file 'context_processors.py'
     from django.utils import timezone as tz
    
     def now_and_today(request):
         now = tz.now()
         return {
             'now': now,
             'today': tz.localtime(now).date(),
         }
    
     # file 'settings.py'
     ...
     TEMPLATES = [
         {
             ...
             'OPTIONS': {
                 'context_processors': [
                     ...
                     'context_processors.now_and_today',
                 ],
             },
         },
     ]
     ...
    

  • 我可以创建一个 自定义模板标签,像这样:

     # file 'my_app/custom_template_tags/custom_time_tags.py'
     from django.utils import timezone as tz
     from django import template
     register = template.Library()
    
     @register.simple_tag
     def get_now(request):
         return tz.now()
    
     @register.simple_tag
     def get_today(request):
         return tz.localtime(tz.now()).date()
    

    像这样使用:

     {% load 'custom_time_tags' %}
    
     {% get_today as today %}
     {% for per in person_list %}
         {% if per.brith_date > today %}
             <p>{{ per.name }} is from the future!!<p>
         {% endif %}
     {% endfor %}
    

  • 我还可以添加一个属性(甚至是 cached_property) 到模型:

     # file 'models.py'
     from django.db import models
     from django.utils import timezone as tz
     from django.utils.functional import cached_property
    
     class Person(models.Model):
         ...
    
         @cached_property
         def is_from_future(self):
             # careful: for long-lived instances do not use 'cached_property' as
             # the time of 'now' might not be right later
             if self.birth_date > tz.localtime(tz.now()).date():
                 return True
    
             return False
    

  • 最后但并非最不重要的是,我可以在视图中进行处理并向元素添加属性:

  • And last but not least, I could just do the processing in the view and add a property to the elements:

     # file 'my_app/views.py'
     from django.utils import timezone as tz
    
     def person_list(request):
         today = tz.localtime(tz.now()).date()
    
         person_list = []
         for p in Person.objects.all():
             p.is_from_future = self.birth_date > today
             person_list.append(p)
    
         return render(request, 'some_template.html', {'person_list': person_list})
    

  • 这篇关于Django 模板 - 是否有一种内置方法可以将当前日期作为“date"类型而不是“str"类型获取?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    相关文章
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆