构建字典列表会产生ValueError

时间:2017-03-05 20:33:40

标签: python list dictionary django-views

我在构建像这样的词典列表时遇到了问题

@login_required(login_url="login/")
def home(request):
    user = StaticHelpers.user_to_subclass(request.user)[1]
    user_type = StaticHelpers.user_to_subclass(request.user)[0]

    if user_type == "Patient":
        apps = StaticHelpers.find_appointments(user)
        events = []
        for app in apps:
            events.append({
                'title': str(app.doctor),
                'start': str(app.start_time),
                'end': str(app.end_time)
            })
        return render(request, 'HealthApp/patientIndex.html', events)
    elif user_type == "Doctor" or user_type == "Nurse":
        return render(request, 'HealthApp/doctorIndex.html')
    elif user_type == "Admin":
        return render(request, 'HealthApp/doctorIndex.html')

每个字典都需要有这3个值,我需要一个列表。但是它只是向我吐出这个错误

Internal Server Error: /
Traceback (most recent call last):
  File "/home/devin-matte/.local/lib/python3.5/site-packages/django/core/handlers/base.py", line 149, in get_response
    response = self.process_exception_by_middleware(e, request)
  File "/home/devin-matte/.local/lib/python3.5/site-packages/django/core/handlers/base.py", line 147, in get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "/home/devin-matte/.local/lib/python3.5/site-packages/django/contrib/auth/decorators.py", line 23, in _wrapped_view
    return view_func(request, *args, **kwargs)
  File "/home/devin-matte/Documents/Healthnet/trunk/HealthApp/views.py", line 23, in home
    return render(request, 'HealthApp/patientIndex.html', events)
  File "/home/devin-matte/.local/lib/python3.5/site-packages/django/shortcuts.py", line 67, in render
    template_name, context, request=request, using=using)
  File "/home/devin-matte/.local/lib/python3.5/site-packages/django/template/loader.py", line 97, in render_to_string
    return template.render(context, request)
  File "/home/devin-matte/.local/lib/python3.5/site-packages/django/template/backends/django.py", line 92, in render
    context = make_context(context, request)
  File "/home/devin-matte/.local/lib/python3.5/site-packages/django/template/context.py", line 291, in make_context
    context.push(original_context)
  File "/home/devin-matte/.local/lib/python3.5/site-packages/django/template/context.py", line 61, in push
    return ContextDict(self, *dicts, **kwargs)
  File "/home/devin-matte/.local/lib/python3.5/site-packages/django/template/context.py", line 20, in __init__
    super(ContextDict, self).__init__(*args, **kwargs)
ValueError: dictionary update sequence element #0 has length 3; 2 is required
[05/Mar/2017 19:56:17] "GET / HTTP/1.1" 500 99419

1 个答案:

答案 0 :(得分:2)

回溯显示问题与创建词典无关,而是与您如何将它们发送到模板有关。 render的第三个参数必须是dict,其中键是您要用来在模板中引用该值的名称。所以:

return render(request, 'HealthApp/patientIndex.html', {"events": events})

现在,您可以在模板中迭代events