错误提示:"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个回答

2

请查看您的字典,确定键或值中是否使用了单引号或双引号!

dict1 = {'hello': 'world', 'programmer's': 'have girlfriend'}

要解决这个问题,你可以简单地将你的字典转换为字符串,然后使用replace方法!

2
urlpatterns = [ 
    path('',HomePageView.as_view(),name='home'),
]

1
你的回答可以通过添加更多关于代码的信息以及它如何帮助提问者来改进。 - Tyler2P

2
错误应该在参数上。请确认参数是一个字典对象。如果它只是一组参数的列表/元组,请只使用一个*(*params)而不是两个*(**params)。这将把列表/元组展开为正确数量的参数。
或者,如果参数来自代码中的其他部分作为JSON文件,请使用json.loads(params),因为JSON对象有时会表现为字符串,因此您需要使用从字符串加载(loads)来将其转换为JSON。
super(HStoreDictionary, self).__init__(value, **params)

希望这有所帮助!

2
在我的情况下,我一个视图中的 get_context_data 返回了 return render(self.request, 'es_connection_error.html', {'error':error}); 在 try/catch 块中,而不是返回 context

2
我在将JSON字符串转换为字典时遇到了问题。 输入:'{\r\n "resource_id": "id",\r\n "resource_type": "resource"\r\n}' 使用dict()将字符串转换为dict会导致错误。正确的方法是使用json模块。例如: json.loads(input_str)

1
我也遇到了类似的问题。解决方法很简单。只需不要尝试在值中输入NULL或None,否则您可能需要使用类似于这样的内容:
dic.update([(key,value)])

1

当我试图使用错误类型的参数调用更新方法时,遇到了这个问题。预期的字典如下:

{'foo': True}

被传递的那个是:

{'foo': "True"}

确保您检查传递的所有参数都是预期类型。

1

我在调用时遇到了这个错误:

dict(my_data)

我用以下代码修复了这个问题:


import json

json.loads(my_data)

如果 my_dict 使用单引号作为键值,例如my_dict = {'single' : true},这个解决方法将会导致另一个错误:Expecting property name enclosed in double quotes - Azhar Uddin Sheikh

0

我遇到了这个问题,这是我解决它的方法(通过执行 eval 和 strip)

aggr = {}
with open("output.txt", "r") as f:
    for line in f.readlines():
        for k, v in dict(eval(line.strip())).items():
            aggr.setdefault(k, 0)
            aggr[k] = aggr[k] + v
    
print(aggr)

print(aggr)

我读取的数据是一个包含字典对象的文本文件。
{'unknown': 298, 'a4a815d631c805ccd10dd2f1548baa57': 9724, '22b5a0ff959ce0b4036716cc0c2df68b': 1341, 'd186fde596dffaab46260765c7fcba61': 2052}
{'unknown': 323, '49e5357782510659cf083356f7d2a1ab': 9826, 'a4a815d631c805ccd10dd2f1548baa57': 9812, 'b615930608b8dcd217de7904d4463efb': 2409}

0
您正在错误地发送一个参数;它应该是一个 字典对象

  • 错误的方式: func(a=r)

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


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