错误提示:"dictionary update sequence element #0 has length 1; 2 is required" 在Django 1.4中。

244

我在Django 1.4上遇到了一个错误消息:

dictionary update sequence element #0 has length 1; 2 is required

当我尝试使用模板标签时,就发生了这件事情,例如:{% 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,一切都很好,但是错误后来又出现了。


请发布显示“values”和“tmp”中内容的代码。由于缺少代码,此问题标记为-1(可能是临时的)。 - ElmoVanKielmo
1
我得到了错误,因为我使用了列表而不是元组。这会引发错误:dict(['A',"b"]),而这个不会:dict([('A',"b")]) - NelsonGon
24个回答

519

我刚遇到了这个问题。我不知道它是否也影响了你的代码,但对于我来说,根本原因是我忘记在url(或在Django 2.0+中的path)函数调用的最后一个参数上添加name=

例如,下面的函数会抛出与问题相同的错误:

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

但是这些确实有效:

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

回溯无效的原因是因为在内部,Django想将给定的位置参数解析为关键字参数kwargs,并且由于字符串是可迭代的,因此开始展开一个非典型的代码路径。请始终在您的URL中使用name=


58
这个答案非常好,因为它涵盖了一个难以找到的模糊错误。即使是经验丰富的Django开发人员也可能会陷入这个特定的陷阱中。 - glarrain
5
зү№еҲ«жҳҜеҰӮжһңжӮЁиҝҳдҪҝз”ЁDjango RestFrameworkзҡ„Router.registerж–№жі•пјҢе®ғзңӢиө·жқҘйқһеёёзӣёдјјпјҢдёҚеҗҢд№ӢеӨ„еңЁдәҺname kwarg... - Risadinha
2
顺便提一下,我在使用Django 2.0风格的path URL时也遇到了这个错误。我忘记使用关键字参数,写成了path('foo/', views.foo, 'foo')。我不得不改为path('foo/', views.foo, name='foo') - inostia
1
我知道现在有点晚了,但这是关于Django如何考虑传递的参数的精彩见解。感谢您的解释。 - Gru
1
这个问题是我在使用Python时遇到的,尽管上下文有所不同,但这个答案对我很有帮助,因为它指引了我关于字符串的可迭代性的方向。简而言之,我传递了一个字符串而不是一个包含字符串和我实际想要迭代的参数的元组。谢谢。 - undefined
显示剩余2条评论

104

我在玩弄字符串和字典时遇到了这个错误。

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

所以要从字符串获取字典,你实际上需要做的是:

dic2 = eval(str1)
dic2
{'taras': 'vaskiv', 'iruna': 'vaskiv'}

或者在安全方面,我们可以使用literal_eval。

from ast import literal_eval

有没有其他的方法来做这件事? - adam shamsudeen
11
使用json.loads(dict1)进行解析。使用eval可能存在安全风险。 - duhaime
1
@duhaime 如果 my_dict 中的 keys 使用了单引号,例如my_dict = {'single' : true},那么这个解决方案会导致另一个错误:Expecting property name enclosed in double quotes - Azhar Uddin Sheikh
@AzharUddinSheikh 你找到将 ' 转换为 " 的方法了吗? - undefined

33

当您尝试以下操作时,会触发问题错误:

>>> 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

除非您展示完整的代码和跟踪信息,否则很难确定问题出在哪里。


6
这证实了问题中没有包含原因。 - ElmoVanKielmo
谢谢你的回答,下次我会复制回溯信息,但是很奇怪,当它发生在模板标签时,在uwsgi重启后,结果正常显示了,所以有结果。 - user2575627
2
@user2575627,为什么你现在不发代码/回溯?更新(编辑)你的问题。 - falsetru
抱歉,我之前没有发布代码/跟踪信息,因为修复服务非常紧急,所以第一次没有复制跟踪信息。 - user2575627
@user2575627,您能否在/home/name/workspace/project/app/data/commands/my_command.py的第60行附近发布代码? - falsetru

19

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

带错误的代码

 url(r"^testing/$", views.testing, "testing")

没有错误的代码

url(r"^testing/$", views.testing, name="testing")

所以我最终以这种方式解决了上述错误。在你的情况下可能会有所不同,所以请检查你在urls.py中的url模式。


1
2019年,同样的stackoverflow答案仍然每次都帮了我。 - curiouscupcake
是的,非常感谢。SO真的是开发人员、科学家和其他人的一个伟大平台。 - hygull

17

以下是我在Django中遇到并解决错误的方法:

含有错误的代码

urlpatterns = [path('home/', views.home, 'home'),]

更正

urlpatterns = [path('home/', views.home, name='home'),]

这也发生在我身上了,谢谢!我们知道这里发生了什么吗? - Validus Oculus
@ValidusOculus 我不太确定,看起来你必须使用kwargs。你可以在这里阅读更多信息:https://docs.djangoproject.com/en/4.0/ref/urls/ - Harshit Gangwar

10
这里是复现的错误。
>>> 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的序列,然后我们遇到了错误,字典没有更新。第二次我在元组内放入了两个元素,字典得到了更新。

我正在使用shortcuts.redirect并尝试将响应发送到外部页面时遇到相同的错误..例如。'[code] return redirect("https://msn.com")[/code]' - roblem

10

解决方案»

通过在url()函数中传递关键字参数name并将其值设置为您的视图名称,例如homehome-view等。

引发错误»

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

正确的方式»

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


4

我遇到了相同的问题,并发现是由于参数错误导致的。 在 views.py 中,我使用了:

return render(request, 'demo.html',{'items', items})    

但我找到了问题所在:{'items', items}。将其更改为{'items': items}解决了问题。

3

我曾经也遇到了同样的问题,结果发现在 urls.py 文件中缺少了 'name' 导致了这个问题。


3

引起此错误的另一种情况:

dict('{"a":1}')  # gives the error

实现您想要的一种方法是使用eval

eval('{"a":1}')  # gives {"a":1}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接