错误:"Django 1.4上的字典更新序列元素#0的长度为1;需要2"

use*_*627 133 python django uwsgi

我在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
Run Code Online (Sandbox Code Playgroud)

当我尝试访问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
Run Code Online (Sandbox Code Playgroud)

代码是:

tmp = Item.objects.where(HE("kv").contains({'key':value}))

if tmp.count() > 0:

    item_id = tmp[0].id,
Run Code Online (Sandbox Code Playgroud)

我只是尝试访问我不理解"更新序列"消息的值.当我使用游标而不是hstore queryset时,该函数可以正常工作.错误来自模板渲染,我刚刚重新启动uwsgi,一切运行良好,但错误稍后会再次出现

[编辑]

有人有想法吗?

Tha*_*all 348

刚遇到这个问题.我不知道它是否与你的代码相同,但对我而言,根本原因是因为我忘记name=url函数调用的最后一个参数.

例如,以下引发了问题的错误:

url(r'^foo/(?P<bar>[A-Za-z]+)/$', views.FooBar.as_view(), 'foo')
path('foo/{slug:bar}/', views.FooBar, 'foo')
Run Code Online (Sandbox Code Playgroud)

但这确实有效:

url(r'^foo/(?P<bar>[A-Za-z]+)/$', views.FooBar.as_view(), name='foo')
path('foo/{slug:bar}/', views.FooBar, name='foo')
Run Code Online (Sandbox Code Playgroud)

回溯无益的原因是因为在内部,Django想要将给定的位置参数解析为关键字参数path,并且由于字符串是可迭代的,因此非典型代码路径开始展开.始终kwargs在您的网址上使用!

  • 这个答案非常好,因为它涵盖了一个难以弄清楚的模糊错误.即使是经验丰富的Django开发者也可能陷入这个特殊陷阱. (31认同)
  • 特别是如果你也使用Django RestFramework的`Router.register`方法.它看起来非常相似,区别在于`name` kwarg ...... (4认同)
  • 好吧,半小时的非生产性花费永远不会回来.TNX. (4认同)
  • 辉煌!正是我忘了:S (2认同)
  • 仅供参考,我使用 Django 2.0 样式的“path” URL 也收到了此错误。忘记使用 kwarg 并且有这个:`path('foo/',views.foo,'foo')`。我必须更改为`path('foo/',views.foo,name='foo')` (2认同)

fal*_*tru 29

当您尝试以下内容时,会引发您的问题中的错误:

>>> 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
Run Code Online (Sandbox Code Playgroud)

除非您显示代码,完整的追溯,否则很难说出代码中的原因.

  • 这证实了原因不包括在问题中. (5认同)
  • @ user2575627,你为什么不现在发布代码/回溯?更新(编辑)您的问题. (2认同)

小智 17

当我搞乱字符串和字典时,我收到了这个错误.

dict1 = {'taras': 'vaskiv', 'iruna': 'vaskiv'}
str1 = str(dict1)
dict(str1)
*** ValueError: dictionary update sequence element #0 has length 1; 2 is required
Run Code Online (Sandbox Code Playgroud)

那么你从字符串中获取dict实际上要做的是:

dic2 = eval(str1)
dic2
{'taras': 'vaskiv', 'iruna': 'vaskiv'}
Run Code Online (Sandbox Code Playgroud)

  • 是的,使用“json.loads(dict1)”。使用“eval”可能会带来安全风险 (3认同)

hyg*_*ull 14

当我忘记将关键字参数名称传递给url()函数时,我遇到了上述问题.

代码有错误

 url(r"^testing/$", views.testing, "testing")
Run Code Online (Sandbox Code Playgroud)

代码没有错误

url(r"^testing/$", views.testing, name="testing")
Run Code Online (Sandbox Code Playgroud)

所以最后我以这种方式删除了上述错误.在你的情况下,它可能会有所不同.因此,请检查urls.py中的网址模式.


Ben*_*ire 10

解"

通过关键字参数名称与值作为您的视图名称,如homehome-view等方面url()发挥作用.

引发错误»

url(r'^home$', 'common.views.view1', 'home'),

正确"

url(r'^home$', 'common.views.view1', name='home'),


nav*_*nam 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
>>> 
Run Code Online (Sandbox Code Playgroud)

如果给出序列并且任何元素长度为1且需要两个,那么我们将得到这种错误.请参阅上面的代码.我第一次给序列添加元组并且它的长度为1,然后我们得到错误并且字典没有更新.第二次我用两个元素给内部元组,字典得到了更新.


Har*_*war 9

以下是我在 Django 中遇到此错误并修复它的方法:

有错误的代码

urlpatterns = [path('home/', views.home, 'home'),]
Run Code Online (Sandbox Code Playgroud)

更正

urlpatterns = [path('home/', views.home, name='home'),]
Run Code Online (Sandbox Code Playgroud)