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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17610732/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 08:40:14  来源:igfitidea点击:

Error: "dictionary update sequence element #0 has length 1; 2 is required" on Django 1.4

pythondjangouwsgi

提问by user2575627

I have an error message on django 1.4:

我在 django 1.4 上有一条错误消息:

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

字典更新序列元素 #0 的长度为 1;2 是必需的

[EDIT]

[编辑]

It happened when I tried using a template tag like: `{% for v in values %}:

当我尝试使用模板标签时发生了这种情况:`{% 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

It happens too when I try to access on a hstore queryset:

当我尝试访问 hstore 查询集时也会发生这种情况:

[edit]

[编辑]

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

the code is:

代码是:

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

if tmp.count() > 0:

    item_id = tmp[0].id,

I'm just trying to access the value. I don't understand the "update sequence" message. When I use a cursor instead of hstore queryset, the function works. The error comes on template rendering too. I just restarted uwsgiand everything works well, but the error comes back later.

我只是想访问该值。我不明白“更新序列”消息。当我使用游标而不是 hstore 查询集时,该功能有效。错误也出现在模板渲染上。我刚刚重新启动uwsgi,一切正常,但稍后错误又回来了。

[edit]

[编辑]

Has someone an idea?

有人有想法吗?

回答by falsetru

Error in your question is raised when you try something like following:

当您尝试以下操作时,您的问题会出现错误:

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

It's hard to tell where is the cause in your code unless you show your code, full traceback.

除非你展示你的代码,完整的回溯,否则很难说你的代码中的原因在哪里。

回答by Thane Brimhall

Just ran into this problem. I don't know if it's the same thing that hit your code, but for me the root cause was because I forgot to put name=on the last argument of the url(or pathin Django 2.0+) function call.

刚遇到这个问题。我不知道它是否与您的代码相同,但对我而言,根本原因是因为我忘记name=url(或path在 Django 2.0+ 中)函数调用的最后一个参数。

For instance, the following functions throw the error from the question:

例如,以下函数从问题中抛出错误:

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

But these actually work:

但这些实际上有效:

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

The reason why the traceback is unhelpful is because internally, Django wants to parse the given positionalargument as the keywordargument kwargs, and since a string is an iterable, an atypical code path begins to unfold. Always use name=on your urls!

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

回答by neotam

Here is the reproduced error.

这是重现的错误。

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

If you give the sequence and any element length is 1 and required two then we will get this kind of error. See the above code. First time I gave the sequence with tuple and it's length 1, then we got the error and dictionary is not updated. second time I gave inside tuple with with two elements, dictionary got updated.

如果您给出序列并且任何元素长度为 1 且需要 2,那么我们将得到此类错误。看上面的代码。我第一次用元组给出序列并且它的长度为 1,然后我们得到了错误并且字典没有更新。第二次我用两个元素给内部元组时,字典得到了更新。

回答by soField

You are sending one parameter incorrectly; it should be a dictionary object:

您错误地发送了一个参数;它应该是dictionary object

  • Wrong:func(a=r)

  • Correct:func(a={'x':y})

  • 错误的:func(a=r)

  • 正确的:func(a={'x':y})

回答by Binoy Babu

I got the same issue and found that it was due to wrong parameters. In views.py, I used:

我遇到了同样的问题,发现是由于参数错误造成的。在 中views.py,我使用了:

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

But I found the issue: {'items', items}. Changing to {'items': items}resolved the issue.

但我发现了这个问题:{'items', items}. 更改以{'items': items}解决问题。

回答by Nick Kobishev

I encountered this issue when trying to invoke the update method with a parameter of a wrong type. The expected dict was:

我在尝试使用错误类型的参数调用更新方法时遇到了这个问题。预期的字典是:

{'foo': True}

The one that was passed was:

通过的是:

{'foo': "True"}

make sure you check all the parameters you pass are of the expected type.

确保检查所有传递的参数是否符合预期类型。

回答by shadi

In my case, my get_context_datain one of my views was returning return render(self.request, 'es_connection_error.html', {'error':error});in a try/catch block instead of returning context

就我而言,我get_context_data的观点之一是return render(self.request, 'es_connection_error.html', {'error':error});在 try/catch 块中返回而不是返回context

回答by hygull

I faced the above mentioned problem when I forgot to pass a keyword argument nameto url() function.

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

Code with error

有错误的代码

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

Code without error

没有错误的代码

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

So finally I removed the above error in this way. It might be something different in your case. So check your url patterns in urls.py.

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

回答by Benjamin McIntire

Solution»

解决方案”

Pass a keyword argument namewith value as your view name e.g homeor home-viewetc. to url()function.

将带有值的关键字参数名称作为您的视图名称(例如homehome-view等)传递给url()函数。

Throws Error»

抛出错误»

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

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

Correct»

正确的”

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

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

回答by Midhun C Nair

The error should be with the params. Please verify that the params is a dictionary object. If it is just a list/tuple of arguments use only one * (*params) instead of two * (**params). This will explode the list/tuple into the proper amount of arguments.

错误应该与参数有关。请验证 params 是一个字典对象。如果它只是一个参数列表/元组,则仅使用一个 * ( *params) 而不是两个 * ( **params)。这会将列表/元组分解为适当数量的参数。

Or, if the params is coming from some other part of code as a JSON file, please do json.loads(params), because the JSON objects sometimes behave as string and so you need to make it as a JSON using load from string (loads).

或者,如果 params 来自代码的其他部分作为 JSON 文件,请这样做json.loads(params),因为 JSON 对象有时表现为字符串,因此您需要使用从字符串加载 (loads) 将其设为 JSON。

super(HStoreDictionary, self).__init__(value, **params)

Hope this helps!

希望这可以帮助!