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

0

当使用以下示例中的get_or_create方法时,也会出现此行为,显然会导致错误:

state,_ = Status.objects.get_or_create('Pending')

要解决这个问题,您需要添加相应的键和值。

例如:state,_ = Status.objects.get_or_create(name='Pending')


救命稻草!需要这个。 - Kwaku Biney

0
请检查您的URL路径,我通过更改URL来解决了这个问题。
使用以下代码: path('reset_password_email/', requestpasswordresetemail, name="request-rest-email")
而不是 path('reset_password_email/', requestpasswordresetemail, "request-rest-email")

你的回答可以通过提供更多支持信息来改进。请编辑以添加进一步的细节,例如引用或文档,以便他人可以确认你的答案是正确的。您可以在帮助中心中找到有关如何编写良好答案的更多信息。 - Community

0

I got this error when I was messing around with string and dictionary.

dict1 = {'taras': 'vaskiv', 'iruna': 'vaskiv'}
str1 = str(dict1)
dict(str1)

or to be specific
query_result = req_db_session.query(app_config_model.APPCONFIG).with_entities(app_config_model.APPCONFIG.value).filter(app_config_model.APPCONFIG.name == 'test_me').first()
print(query_result, type(query_result))
print('--------------------------')
print(type(query_result))
# prints <class 'sqlalchemy.util._collections.result'>
print(dict(query_result))
# throws error

*** ValueError: dictionary update sequence element #0 has length 1; 2 is required So what you actually worked was:

query_result = req_db_session.query(app_config_model.APPCONFIG).with_entities(app_config_model.APPCONFIG.value).filter(app_config_model.APPCONFIG.name == 'test_me').first()
print(query_result, type(query_result))
print('--------------------------')
print(type(query_result.value))
# prints <type 'unicode'>
print(json.loads(query_result.value))
# prints parsed dictionary


0
from ast import literal_eval

c = "{'taras': 'vaskiv', 'iruna': 'vaskiv'}"
c= dict(literal_eval(c))

2
欢迎来到Stack Overflow!虽然这段代码可能解决了问题,但包括解释如何以及为什么解决问题会真正有助于提高您的帖子质量,可能会得到更多赞。请记住,您正在回答未来读者的问题,而不仅是现在提问的人。请[编辑]您的答案以添加解释,并指出适用的限制和假设。 - Yunnosch
目前你的回答不够清晰。请编辑并添加更多细节,以帮助其他人理解它如何回答所提出的问题。你可以在帮助中心找到有关如何撰写好答案的更多信息。 - Community

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