【问题标题】:dictionary update sequence element #0 has length 15; 2 is required字典更新序列元素#0的长度为15; 2 是必需的
【发布时间】:2014-10-16 15:10:21
【问题描述】:

我正在将我的 python/django 应用程序从 1.6.5 升级到 1.7。我无法解决以下错误:字典更新序列元素 #0 的长度为 15; 2 是必需的

这是回溯输出:

Request Method: GET
Request URL: http://127.0.0.1:8000/dashboard/

Django Version: 1.7
Python Version: 2.7.5
Installed Applications:
('django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'django.contrib.sites',
 'django.contrib.humanize',
 'bootstrap3',
 'ajax_select',
 'appconf',
 'versiontools',
 'compressor',
 'googlecharts',
 'django_extensions',
 'mandala',
 'locations',
 'statistics',
 'alarms',
 'accounts',
 'assets')
Installed Middleware:
('django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware')


Traceback:
File "/Users/CLDSupportSystems/mandala-system/mandala_env_django_1.7/lib/python2.7/sit-packages/django/core/handlers/base.py" in get_response
111.                     response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/Users/CLDSupportSystems/mandala-system/mandala_env_django_1.7/lib/python2.7/site-packages/django/contrib/auth/decorators.py" in _wrapped_view
  22.                 return view_func(request, *args, **kwargs)
File "/Users/CLDSupportSystems/mandala-system/mandala_env_django_1.7/mandala/mandala/views.py" in dashboard
  117.         return render_to_response('dashboard/dashboard.html', variables,context_instance=RequestContext(request))
File "/Users/CLDSupportSystems/mandala-system/mandala_env_django_1.7/lib/python2.7/site-packages/django/shortcuts.py" in render_to_response
  23.     return HttpResponse(loader.render_to_string(*args, **kwargs), **httpresponse_kwargs)
File "/Users/CLDSupportSystems/mandala-system/mandala_env_django_1.7/lib/python2.7/site-packages/django/template/loader.py" in render_to_string
  177.     with context_instance.push(dictionary):
File "/Users/CLDSupportSystems/mandala-system/mandala_env_django_1.7/lib/python2.7/site-packages/django/template/context.py" in push
  54.         return ContextDict(self, *args, **kwargs)
File "/Users/CLDSupportSystems/mandala-system/mandala_env_django_1.7/lib/python2.7/site-packages/django/template/context.py" in __init__
  19.         super(ContextDict, self).__init__(*args, **kwargs)

Exception Type: ValueError at /dashboard/
Exception Value: dictionary update sequence element #0 has length 15; 2 is required

以下行抛出错误:

return render_to_response('dashboard/dashboard.html', variables,context_instance=RequestContext(request))

这里是变量的定义:

variables = RequestContext(request, {
    'fresh_locations': fresh_data_locations,
    'webalert_locations': webalert_locations,
    'locations_reporting': reporting_locations,
    'locations_not_reporting': locations_not_reporting,
    'inalarm_count': inalarm_count,
    'inalarm_stores': inalarm_stores_qs,
    'workspace_count': workspace_count,
    'user_profile': user_profile,
})

谁能指出我正确的方向?

【问题讨论】:

  • 我强烈怀疑variables 应该是普通字典,而不是RequestContext

标签: python django python-2.7 sequence django-1.7


【解决方案1】:

render_to_response() 的第二个参数必须是字典。你正在传递一个RequestContext()

删除RequestContext() 对象并使variables 只是字典:

variables = {
    'fresh_locations': fresh_data_locations,
    'webalert_locations': webalert_locations,
    'locations_reporting': reporting_locations,
    'locations_not_reporting': locations_not_reporting,
    'inalarm_count': inalarm_count,
    'inalarm_stores': inalarm_stores_qs,
    'workspace_count': workspace_count,
    'user_profile': user_profile,
}

【讨论】:

  • 谢谢。它适用于我正在使用的那个视图。我从以前的程序员那里接手,直到更新到 1.7。我回顾了 1.6,render_to_response 中似乎没有任何变化。你知道为什么它以前可以工作吗?跨度>
  • @Brandon:我怀疑它曾经奏效是巧合;文档清楚地表明需要一本字典。
  • 好的。非常感谢。如此简单,我错过了。非常感谢。
【解决方案2】:

这是因为 render_to_response() 和 render() 快捷方式会自动将 RequestContext 应用于上下文变量(您的变量目录)。这肯定是一个错字,但为什么在你问之前它就起作用了?

它本来可以在 1.6 中运行,但是 django.template.context 中的 RequestContext 实现在 1.7 中发生了变化。它被分解为更加面向对象并进行了优化以提高效率。历史就在这里,我想它是

https://github.com/django/django/commits/master/django/template/context.py

这个提交特别优化了RequestContext:

https://github.com/django/django/commit/8d473b2c54035cbcd3aacef0cb83a9769cd05ad3

这里是如何重现错误:

>>> from django.template import RequestContext
>>> from django.test.client import RequestFactory
>>> request_factory = RequestFactory()
>>> request = request_factory.get('www.google.com')
>>> fresh_data_locations, webalert_locations, reporting_locations, locations_not_reporting, inalarm_count, inalarm_stores_qs, workspace_count, user_profile = '', '', '', '', '', '', '', ''
>>> variables = RequestContext(request, {
...     'fresh_locations': fresh_data_locations,
...     'webalert_locations': webalert_locations,
...     'locations_reporting': reporting_locations,
...     'locations_not_reporting': locations_not_reporting,
...     'inalarm_count': inalarm_count,
...     'inalarm_stores': inalarm_stores_qs,
...     'workspace_count': workspace_count,
...     'user_profile': user_profile,
... })
>>> variables
[{'False': False, 'None': None, 'True': True}, {'workspace_count': '', 'locations_not_reporting': '', 'fresh_locations': '', 'inalarm_stores': '', 'locations_reporting': '', 'webalert_locations': '', 'user_profile': '', 'inalarm_count': ''}, {u'csrf_token': <django.utils.functional.__proxy__ object at 0x10439fcd0>, u'sql_queries': [], 'perms': <django.contrib.auth.context_processors.PermWrapper object at 0x10439fe50>, 'messages': [], u'request': <WSGIRequest
path:/www.google.com,
GET:<QueryDict: {}>,
POST:<QueryDict: {}>,
COOKIES:{},
META:{u'HTTP_COOKIE': u'',
 u'PATH_INFO': u'www.google.com',
 u'QUERY_STRING': '',
 u'REMOTE_ADDR': '127.0.0.1',
 u'REQUEST_METHOD': 'GET',
 u'SCRIPT_NAME': u'',
 u'SERVER_NAME': 'testserver',
 u'SERVER_PORT': '80',
 u'SERVER_PROTOCOL': 'HTTP/1.1',
 u'wsgi.errors': <_io.BytesIO object at 0x1042fce30>,
 u'wsgi.input': <django.test.client.FakePayload object at 0x104391550>,
 u'wsgi.multiprocess': True,
 u'wsgi.multithread': False,
 u'wsgi.run_once': False,
 u'wsgi.url_scheme': 'http',
 u'wsgi.version': (1, 0)}>, 'api_header': {'content-type': 'application/json', 'Authorization': 'YmFrZXItYXBpOlVuaW9uMTIz'}, u'STATIC_URL': '/static/', u'LANGUAGES': (('en', 'English'),), 'api_address': 'http://69.164.69.214/BakerPublic/api', 'user': <django.contrib.auth.models.AnonymousUser object at 0x10439fe10>, u'LANGUAGE_CODE': u'en-us', u'debug': True, 'DEFAULT_MESSAGE_LEVELS': {'DEBUG': 10, 'INFO': 20, 'WARNING': 30, 'SUCCESS': 25, 'ERROR': 40}, u'LANGUAGE_BIDI': False, u'MEDIA_URL': '/media/'}]
>>> type(variables)
<class 'django.template.context.RequestContext'>
>>> dict(variables)
Traceback (most recent call last):
  File "<console>", line 1, in <module>
ValueError: dictionary update sequence element #0 has length 15; 2 is required

所以使用 django 1.6 dir() 函数返回没有错误,但使用 1.7 实现它失败了。在 1.7 之前,您所采用的其中一项几乎可以说是巧合。

当使用来自 django.views.generic 的基于类的视图时,很多这些东西都是为你完成的。如果您查看 TemplateView,您会看到它从 TemplateResponseMixin 继承了 render_to_response 方法,该方法使用 TemplateResponse 来完成所有这些工作。另请查看具有 get_context_data 方法的 ContextMixin。我认为将上下文数据传递给模板的最简洁方式。更多关于泛型/基于类的视图here

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-04-06
    • 2016-06-30
    • 1970-01-01
    • 2015-02-22
    • 2019-08-10
    • 2021-04-01
    相关资源
    最近更新 更多