我正在将我的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,
})
有人能指出我正确的方向吗?
答案 0 :(得分:3)
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 :(得分:0)
这是因为render_to_response()和render()快捷方式会自动对上下文变量(你的变量dir)应用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。另请查看ContextMixin,它具有get_context_data方法。我认为最简单的方法是将上下文数据传递给模板。有关基于通用/类的视图的更多信息here。