TypeError:“ datetime.date”对象不可下标

时间:2019-07-30 08:14:13

标签: django django-templates django-custom-tags

我正在尝试创建一个带有3个参数的自定义模板标签。我正在尝试计算两个日期之间的天数,同时从该计数中排除周末天数。根据部门的不同,每个用户的周末也不相同。因此,我需要将start_dateend_dateuser_id传递到模板标记函数中。这是我到目前为止所做的:

from django import template
from datetime import datetime, timedelta, date

register = template.Library()

@register.filter('date_diff_helper')
def date_diff_helper(startdate, enddate):
    return [startdate, enddate]

@register.filter(name='date_diff')
def date_diff(dates, user_id):

    start_date = dates[0]
    end_date = dates[1]

    count = 0
    weekends = ["Friday", "Saturday"]

    for days in range((end_date - start_date).days + 1):

        if start_date.strftime("%A") not in weekends:
            count += 1
        else:
            start_date += timedelta(days=1)
            continue

        if start_date == end_date:
            break

        start_date += timedelta(days=1)

    return count

这就是我在模板中调用这些函数的方式:

{{ leave.start_date|date_diff_helper:leave.end_date|date_diff:leave.emp_id }}

运行代码时,它使我TypeError'datetime.date' object is not subscriptable。当我尝试检查dates函数中date_diff参数的类型时,它说:

  

<类“列表”>

     

<类'datetime.date'>

但是,当尝试将start_date分配为第一个日期对象时(如start_date = dates [0]),它甚至会引发错误。这是错误的完整回溯:

Traceback:

File "C:\Users\Naeem.Khan\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\handlers\exception.py" in inner
  34.             response = get_response(request)

File "C:\Users\Naeem.Khan\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\handlers\base.py" in _get_response
  115.                 response = self.process_exception_by_middleware(e, request)

File "C:\Users\Naeem.Khan\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\handlers\base.py" in _get_response
  113.                 response = wrapped_callback(request, *callback_args, **callback_kwargs)

File "C:\Users\Naeem.Khan\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\views\generic\base.py" in view
  71.             return self.dispatch(request, *args, **kwargs)

File "C:\Users\Naeem.Khan\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\views\generic\base.py" in dispatch
  97.         return handler(request, *args, **kwargs)

File "C:\Projects\LMS\LMSAdmin\views.py" in get
  203.         return render(request, self.template_name, {'leave_requests': leave_requests})

File "C:\Users\Naeem.Khan\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\shortcuts.py" in render
  36.     content = loader.render_to_string(template_name, context, request, using=using)

File "C:\Users\Naeem.Khan\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\template\loader.py" in render_to_string
  62.     return template.render(context, request)

File "C:\Users\Naeem.Khan\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\template\backends\django.py" in render
  61.             return self.template.render(context)

File "C:\Users\Naeem.Khan\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\template\base.py" in render
  171.                     return self._render(context)

File "C:\Users\Naeem.Khan\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\template\base.py" in _render
  163.         return self.nodelist.render(context)

File "C:\Users\Naeem.Khan\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\template\base.py" in render
  937.                 bit = node.render_annotated(context)

File "C:\Users\Naeem.Khan\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\template\base.py" in render_annotated
  904.             return self.render(context)

File "C:\Users\Naeem.Khan\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\template\loader_tags.py" in render
  150.             return compiled_parent._render(context)

File "C:\Users\Naeem.Khan\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\template\base.py" in _render
  163.         return self.nodelist.render(context)

File "C:\Users\Naeem.Khan\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\template\base.py" in render
  937.                 bit = node.render_annotated(context)

File "C:\Users\Naeem.Khan\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\template\base.py" in render_annotated
  904.             return self.render(context)

File "C:\Users\Naeem.Khan\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\template\loader_tags.py" in render
  62.                 result = block.nodelist.render(context)

File "C:\Users\Naeem.Khan\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\template\base.py" in render
  937.                 bit = node.render_annotated(context)

File "C:\Users\Naeem.Khan\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\template\base.py" in render_annotated
  904.             return self.render(context)

File "C:\Users\Naeem.Khan\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\template\defaulttags.py" in render
  209.                     nodelist.append(node.render_annotated(context))

File "C:\Users\Naeem.Khan\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\template\base.py" in render_annotated
  904.             return self.render(context)

File "C:\Users\Naeem.Khan\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\template\base.py" in render
  987.             output = self.filter_expression.resolve(context)

File "C:\Users\Naeem.Khan\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\template\base.py" in resolve
  698.                 new_obj = func(obj, *arg_vals)

File "C:\Projects\LMS\LMSAdmin\templatetags\LMSAdmin_tags.py" in date_diff
  38.     start_date = dates[0]

Exception Type: TypeError at /lms_admin/SeniorManagementAdmin/
Exception Value: 'datetime.date' object is not subscriptable

我已经在这个问题上坚持了很长时间。我是Django和Python的初学者,因此对您的帮助将不胜感激。


编辑:

这是我检查dates变量类型的方法:

def date_diff(dates, user_id):

    print(type(dates))

    #if I removed these two lines, the result is only < class 'list'> 
    start_date = dates[0] 
    end_date = dates[1]
    ...

当我访问该页面时,它将在控制台中打印出类型为列表和日期时间。但是,如果删除上面的start_date和end_date变量,则仅打印。我不了解这种行为。


1 个答案:

答案 0 :(得分:1)

  

当我运行代码时,它给我TypeError说'datetime.date'对象是不能下标的。当我尝试检查date_diff函数中的dates参数类型时,它说:

     

<类“列表”>

     

<类'datetime.date'>

这表明您实际上对模板中的过滤器进行了两次调用-第一个是正确的,第二个是错误的。