Search code examples
djangodjango-templatesdjango-custom-tags

TypeError: 'datetime.date' object is not subscriptable


I'm trying to create a custom template tag which takes 3 arguments. I'm trying to calculate the number of days between two dates, while excluding the weekends days from that count. And depending on the department, the weekend is different for each user. So I need start_date, end_date, user_id to be passed onto the template tag function. This is what I have done so far:

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

This is how I'm calling these functions in template:

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

When I run the code, it gives me TypeError saying 'datetime.date' object is not subscriptable. When I tried to check the type of dates parameter in date_diff function, it says:

< class 'list'>

< class 'datetime.date'>

But when it tries to assign start_date as the first date object, as in start_date = dates[0], it throws the error even. Here is a complete traceback of the error:

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

I'm a beginner to Django and Python.

Edit

This is how I checked the type of dates variable:

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]
    ...

When I visit the page, it prints out in console that the type is list and datetime. But if I remove the above start_date and end_date variables, it prints out < class 'list'> only. I do not understand this behavior.



Solution

  • When I run the code, it gives me TypeError saying 'datetime.date' object is not subscriptable. When I tried to check the type of dates parameter in date_diff function, it says:

    < class 'list'>

    < class 'datetime.date'>

    This suggests that you actually have two calls to the filter in your template - the first one being correct and the second one incorrect.