我在django 1.4上有一条错误消息:
字典更新序列元素#0的长度为1; 2是必需的
[编辑]
当我尝试使用模板标签时发生了这样的事情:`{%for v in values%}:
dictionary update sequence element #0 has length 1; 2 is required
Request Method: GET
Request URL: ...
Django Version: 1.4.5
Exception Type: ValueError
Exception Value:
dictionary update sequence element #0 has length 1; 2 is required
Exception Location: /usr/local/lib/python2.7/dist-packages/djorm_hstore/fields.py in __init__, line 21
Python Executable: /usr/bin/uwsgi-core
Python Version: 2.7.3
Python Path:
['/var/www/',
'.',
'',
'/usr/lib/python2.7',
'/usr/lib/python2.7/plat-linux2',
'/usr/lib/python2.7/lib-tk',
'/usr/lib/python2.7/lib-old',
'/usr/lib/python2.7/lib-dynload',
'/usr/local/lib/python2.7/dist-packages',
'/usr/lib/python2.7/dist-packages',
'/usr/lib/python2.7/dist-packages/PIL',
'/usr/lib/pymodules/python2.7']
Server time: sam, 13 Jul 2013 16:15:45 +0200
Error during template rendering
In template /var/www/templates/app/index.html, error at line 172
dictionary update sequence element #0 has length 1; 2 is required
172 {% for product in products %}
Traceback Switch to copy-and-paste view
/usr/lib/python2.7/dist-packages/django/core/handlers/base.py in get_response
response = callback(request, *callback_args, **callback_kwargs)
...
▶ Local vars
/usr/lib/python2.7/dist-packages/django/contrib/auth/decorators.py in _wrapped_view
return view_func(request, *args, **kwargs)
...
▶ Local vars
/usr/lib/python2.7/dist-packages/django/views/decorators/http.py in inner
return func(request, *args, **kwargs)
...
▶ Local vars
./app/views.py in index
context_instance=RequestContext(request))
...
▶ Local vars
/usr/lib/python2.7/dist-packages/django/shortcuts/__init__.py in render_to_response
return HttpResponse(loader.render_to_string(*args, **kwargs), **httpresponse_kwargs)
...
▶ Local vars
/usr/lib/python2.7/dist-packages/django/template/loader.py in render_to_string
return t.render(context_instance)
...
▶ Local vars
/usr/lib/python2.7/dist-packages/django/template/base.py in render
return self._render(context)
...
▶ Local vars
/usr/lib/python2.7/dist-packages/django/template/base.py in _render
return self.nodelist.render(context)
...
▶ Local vars
/usr/lib/python2.7/dist-packages/django/template/base.py in render
bit = self.render_node(node, context)
...
▶ Local vars
/usr/lib/python2.7/dist-packages/django/template/debug.py in render_node
return node.render(context)
...
▶ Local vars
/usr/lib/python2.7/dist-packages/django/template/loader_tags.py in render
return compiled_parent._render(context)
...
▶ Local vars
/usr/lib/python2.7/dist-packages/django/template/base.py in _render
return self.nodelist.render(context)
...
▶ Local vars
/usr/lib/python2.7/dist-packages/django/template/base.py in render
bit = self.render_node(node, context)
...
▶ Local vars
/usr/lib/python2.7/dist-packages/django/template/debug.py in render_node
return node.render(context)
...
▶ Local vars
/usr/lib/python2.7/dist-packages/django/template/loader_tags.py in render
result = block.nodelist.render(context)
...
▶ Local vars
/usr/lib/python2.7/dist-packages/django/template/base.py in render
bit = self.render_node(node, context)
...
▶ Local vars
/usr/lib/python2.7/dist-packages/django/template/debug.py in render_node
return node.render(context)
...
▶ Local vars
/usr/lib/python2.7/dist-packages/django/template/defaulttags.py in render
len_values = len(values)
...
▶ Local vars
/usr/lib/python2.7/dist-packages/django/core/paginator.py in __len__
return len(self.object_list)
...
▶ Local vars
/usr/lib/python2.7/dist-packages/django/db/models/query.py in __len__
self._result_cache = list(self.iterator())
...
▶ Local vars
/usr/lib/python2.7/dist-packages/django/db/models/query.py in iterator
obj = model(*row[index_start:aggregate_start])
...
▶ Local vars
/usr/lib/python2.7/dist-packages/django/db/models/base.py in __init__
setattr(self, field.attname, val)
...
▶ Local vars
/usr/local/lib/python2.7/dist-packages/djorm_hstore/fields.py in __set__
value = self.field._attribute_class(value, self.field, obj)
...
▶ Local vars
/usr/local/lib/python2.7/dist-packages/djorm_hstore/fields.py in __init__
super(HStoreDictionary, self).__init__(value, **params)
...
▶ Local vars
当我尝试访问hstore查询集时也会发生这种情况:
[编辑]
Traceback (most recent call last):
File "manage.py", line 14, in <module>
execute_manager(settings)
File "/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.py", line 459, in execute_manager
utility.execute()
File "/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.py", line 382, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/usr/local/lib/python2.7/dist-packages/django/core/management/base.py", line 196, in run_from_argv
self.execute(*args, **options.__dict__)
File "/usr/local/lib/python2.7/dist-packages/django/core/management/base.py", line 232, in execute
output = self.handle(*args, **options)
File "/home/name/workspace/project/app/data/commands/my_command.py", line 60, in handle
item_id = tmp[0].id,
File "/usr/local/lib/python2.7/dist-packages/django/db/models/query.py", line 207, in __getitem__
return list(qs)[0]
File "/usr/local/lib/python2.7/dist-packages/django/db/models/query.py", line 87, in __len__
self._result_cache.extend(self._iter)
File "/usr/local/lib/python2.7/dist-packages/django/db/models/query.py", line 301, in iterator
obj = model(*row[index_start:aggregate_start])
File "/usr/local/lib/python2.7/dist-packages/django/db/models/base.py", line 300, in __init__
setattr(self, field.attname, val)
File "/usr/local/lib/python2.7/dist-packages/djorm_hstore/fields.py", line 38, in __set__
value = self.field._attribute_class(value, self.field, obj)
File "/usr/local/lib/python2.7/dist-packages/djorm_hstore/fields.py", line 21, in __init__
super(HStoreDictionary, self).__init__(value, **params)
ValueError: dictionary update sequence element #0 has length 1; 2 is required
代码是:
tmp = Item.objects.where(HE("kv").contains({'key':value}))
if tmp.count() > 0:
item_id = tmp[0].id,
我只想尝试访问该值。我不明白“更新序列”消息。当我使用游标而不是hstore queryset时,该函数可以正常工作。错误也出现在模板渲染上。我刚刚重新启动uwsgi
,一切正常,但错误会在稍后发生。
[编辑]
有人有想法吗?
答案 0 :(得分:318)
刚遇到这个问题。我不知道它是否与你的代码相同,但对我而言,根本原因是因为我忘了将name=
放在url
函数调用的最后一个参数上。
例如,以下内容引发了问题的错误:
url(r'^foo/(?P<bar>[A-Za-z]+)/$', FooBar.as_view(), 'foo')
但这确实有效:
url(r'^foo/(?P<bar>[A-Za-z]+)/$', FooBar.as_view(), name='foo')
回溯无用的原因是因为在内部,Django想要将给定的位置参数解析为关键字参数kwargs
,并且因为字符串是一个可迭代的,非典型的代码路径开始展开。始终在您的网址上使用name=
!
答案 1 :(得分:25)
当您尝试以下内容时,会引发您的问题错误:
>>> a_dictionary = {}
>>> a_dictionary.update([[1]])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: dictionary update sequence element #0 has length 1; 2 is required
除非您展示代码,完全追溯,否则很难说出代码中的原因。
答案 2 :(得分:13)
当我忘记将关键字参数名称传递给url()函数时,我遇到了上述问题。
错误代码
url(r"^testing/$", views.testing, "testing")
无错误的代码
url(r"^testing/$", views.testing, name="testing")
所以最后我以这种方式删除了上述错误。在你的情况下,它可能会有所不同。因此,请检查 urls.py 中的网址格式。
答案 3 :(得分:10)
当我弄乱字符串和字典时,我收到了这个错误。
dict1 = {'taras': 'vaskiv', 'iruna': 'vaskiv'}
str1 = str(dict1)
dict(str1)
*** ValueError: dictionary update sequence element #0 has length 1; 2 is required
所以你实际上要从字符串中获取dict是:
dic2 = eval(str1)
dic2
{'taras': 'vaskiv', 'iruna': 'vaskiv'}
答案 4 :(得分:9)
将带有值的关键字参数 name 作为您的视图名称,例如home
或home-view
等传递给url()
函数。
url(r'^home$', 'common.views.view1', 'home'),
url(r'^home$', 'common.views.view1', name='home'),
答案 5 :(得分:9)
这是再现的错误。
>>> d = {}
>>> d.update([(1,)])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: dictionary update sequence element #0 has length 1; 2 is required
>>>
>>> d
{}
>>>
>>> d.update([(1, 2)])
>>> d
{1: 2}
>>>
>>> d.update('hello_some_string')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: dictionary update sequence element #0 has length 1; 2 is required
>>>
如果给出序列并且任何元素长度为1且需要两个,那么我们将得到这种错误。 请参阅上面的代码。我第一次用序列给出了序列,它的长度为1,然后我们得到了错误,字典没有更新。第二次我用两个元素给内部元组,字典得到了更新。
答案 6 :(得分:3)
我遇到了同样的问题,发现这是由于错误的参数造成的。
在views.py
中,我使用了:
return render(request, 'demo.html',{'items', items})
但我发现了这个问题:{'items', items}
。更改为{'items': items}
解决了问题。
答案 7 :(得分:2)
就我而言,我的一个观点中的get_context_data
在try / catch块中返回return render(self.request, 'es_connection_error.html', {'error':error});
而不是返回context
答案 8 :(得分:2)
错误应该是params。 请验证params是字典对象。如果它只是参数的列表/元组,则只使用一个*(*params
)而不是两个*(**params
)。这会将list / tuple分解为适当数量的参数。
或者,如果params来自代码的其他部分作为JSON文件,请执行json.loads(params)
,因为JSON对象有时表现为字符串,因此您需要使用来自的加载来使其成为JSON string(loads)。
super(HStoreDictionary, self).__init__(value, **params)
希望这有帮助!
答案 9 :(得分:2)
这是我在Django中遇到此错误并对其进行修复的方式:
urlpatterns = [path('home/', views.home, 'home'),]
urlpatterns = [path('home/', views.home, name='home'),]
答案 10 :(得分:1)
尝试使用错误类型的参数调用update方法时遇到此问题。 预期的决定是:
{'foo': True}
通过的是:
{'foo': "True"}
确保检查传递的所有参数是否为预期类型。
答案 11 :(得分:0)
您发送的参数不正确;它应该是dictionary object
:
错误: func(a=r)
正确: func(a={'x':y})
答案 12 :(得分:0)
我也有类似类型的问题。解决方法很简单。只是不要尝试在值中输入NULL或None值,否则您可能必须使用类似这样的内容
dic.update([(key,value)])
答案 13 :(得分:0)
我遇到此错误呼叫:
// enable data binding inside module
dataBinding.apply {
isEnabled = true
}
我通过以下方式解决了此问题:
dict(my_data)
答案 14 :(得分:0)
在以下示例中使用 get_or_create
方法时也会发生此行为,显然会出现该错误:
state,_ = Status.objects.get_or_create('Pending')
要解决此问题,您将添加相应的键和值。
就是这样state,_ = Status.objects.get_or_create(name='Pending')
答案 15 :(得分:0)
导致此错误的另一种情况:
dict('{"a":1}') # gives the error
实现您想要的正确方法是使用 eval
eval('{"a":1}') # gives {"a":1}
答案 16 :(得分:0)
检查你的字典你的键或值中是否有单引号或双引号!
export const getData = (tk, values) =>
values
.map(value =>
apiInstance.request({
url: ENDPOINTS.ENDPOINT,
method: 'POST',
data: qs.stringify({
token: token,
category: value,
}),
})
.then(response => {
return response.data;
})
.catch(error => {
return Promise.reject(error.message);
})
);
要解决它,您只需将字典转换为字符串,然后使用替换方法即可!