问题:“无法解包的值太多”异常

我正在Django中进行项目开发,我刚刚开始尝试扩展User模型以创建用户个人资料。

不幸的是,我遇到一个问题:每次尝试在模板(user.get_template.lastIP例如)中获取用户的个人资料时,都会出现以下错误:

环境:

请求方法:GET
要求网址:http:// localhost:8000 /
Django版本:1.1
Python版本:2.6.1

模板错误:
在模板/path/to/base.tpl中,第19行出现错误
   渲染时遇到异常:太多值无法解压

19:您好,{{user.username}}({{user.get_profile.rep}})。近况如何?登出


异常类型:/处的TemplateSyntaxError
异常值:渲染时捕获到异常:太多值无法解包

关于发生了什么或我做错了什么的任何想法?

I’m working on a project in Django and I’ve just started trying to extend the User model in order to make user profiles.

Unfortunately, I’ve run into a problem: Every time I try to get the user’s profile inside of a template (user.get_template.lastIP, for example), I get the following error:

Environment:

Request Method: GET
Request URL: http://localhost:8000/
Django Version: 1.1
Python Version: 2.6.1

Template error:
In template /path/to/base.tpl, error at line 19
   Caught an exception while rendering: too many values to unpack

19 :                Hello, {{user.username}} ({{ user.get_profile.rep}}). How's it goin? Logout


Exception Type: TemplateSyntaxError at /
Exception Value: Caught an exception while rendering: too many values to unpack

Any ideas as to what’s going on or what I’m doing wrong?


回答 0

该异常意味着您正试图解压缩一个元组,但是相对于目标变量的数量,该元组的值太多。例如:这项工作,先打印1,然后打印2,然后打印3

def returnATupleWithThreeValues():
    return (1,2,3)
a,b,c = returnATupleWithThreeValues()
print a
print b
print c

但这会引发您的错误

def returnATupleWithThreeValues():
    return (1,2,3)
a,b = returnATupleWithThreeValues()
print a
print b

加薪

Traceback (most recent call last):
  File "c.py", line 3, in ?
    a,b = returnATupleWithThreeValues()
ValueError: too many values to unpack

现在,我不知道在您的情况下发生这种情况的原因,但也许此答案将为您指明正确的方向。

That exception means that you are trying to unpack a tuple, but the tuple has too many values with respect to the number of target variables. For example: this work, and prints 1, then 2, then 3

def returnATupleWithThreeValues():
    return (1,2,3)
a,b,c = returnATupleWithThreeValues()
print a
print b
print c

But this raises your error

def returnATupleWithThreeValues():
    return (1,2,3)
a,b = returnATupleWithThreeValues()
print a
print b

raises

Traceback (most recent call last):
  File "c.py", line 3, in ?
    a,b = returnATupleWithThreeValues()
ValueError: too many values to unpack

Now, the reason why this happens in your case, I don’t know, but maybe this answer will point you in the right direction.


回答 1

尝试解压缩一个变量,

python会将其作为列表处理,

然后从清单中打开包装

def returnATupleWithThreeValues():
    return (1,2,3)
a = returnATupleWithThreeValues() # a is a list (1,2,3)
print a[0] # list[0] = 1
print a[1] # list[1] = 2
print a[2] # list[2] = 3

try unpacking in one variable,

python will handle it as a list,

then unpack from the list

def returnATupleWithThreeValues():
    return (1,2,3)
a = returnATupleWithThreeValues() # a is a list (1,2,3)
print a[0] # list[0] = 1
print a[1] # list[1] = 2
print a[2] # list[2] = 3

回答 2

这个问题看起来很熟悉,所以我想我可以看看能否从有限的信息中进行复制。

快速搜索在James Bennett的博客中找到了一个条目,其中提到在使用UserProfile扩展User模型时,settings.py中的常见错误可能导致Django抛出此错误。

引用博客条目:

该设置的值不是“ appname.models.modelname”,而只是“ appname.modelname”。原因是Django没有使用它进行直接导入。相反,它使用内部模型加载功能,该功能仅需要应用程序的名称和模型的名称。尝试在AUTH_PROFILE_MODULE设置中执行“ appname.models.modelname”或“ projectname.appname.models.modelname”之类的操作会导致Django崩溃,并出现可怕的“太多值无法解包”错误,因此请确保您已经将“ appname.modelname”放在AUTH_PROFILE_MODULE的值中,不要输入其他任何内容。

如果OP复制了更多的回溯,我希望看到类似下面的内容,可以通过在我的AUTH_PROFILE_MODULE设置中添加“模型”来进行复制。

TemplateSyntaxError at /

Caught an exception while rendering: too many values to unpack

Original Traceback (most recent call last):
  File "/home/brandon/Development/DJANGO_VERSIONS/Django-1.0/django/template/debug.py", line 71, in render_node
    result = node.render(context)
  File "/home/brandon/Development/DJANGO_VERSIONS/Django-1.0/django/template/debug.py", line 87, in render
    output = force_unicode(self.filter_expression.resolve(context))
  File "/home/brandon/Development/DJANGO_VERSIONS/Django-1.0/django/template/__init__.py", line 535, in resolve
    obj = self.var.resolve(context)
  File "/home/brandon/Development/DJANGO_VERSIONS/Django-1.0/django/template/__init__.py", line 676, in resolve
    value = self._resolve_lookup(context)
  File "/home/brandon/Development/DJANGO_VERSIONS/Django-1.0/django/template/__init__.py", line 711, in _resolve_lookup
    current = current()
  File "/home/brandon/Development/DJANGO_VERSIONS/Django-1.0/django/contrib/auth/models.py", line 291, in get_profile
    app_label, model_name = settings.AUTH_PROFILE_MODULE.split('.')
ValueError: too many values to unpack

我认为这是Django仍然具有一些导入魔术的少数情况之一,当小错误未引发预期的异常时,该魔术往往会引起混乱。

您可以在回溯结束时看到,我发布了如何对AUTH_PROFILE_MODULE使用除形式为“ appname.modelname”以外的任何内容会导致“ app_label,model_name = settings.AUTH_PROFILE_MODULE.split(’。’)”这一行引发“无法解包的值太多”错误。

我99%确信这是这里遇到的原始问题。

This problem looked familiar so I thought I’d see if I could replicate from the limited amount of information.

A quick search turned up an entry in James Bennett’s blog here which mentions that when working with the UserProfile to extend the User model a common mistake in settings.py can cause Django to throw this error.

To quote the blog entry:

The value of the setting is not “appname.models.modelname”, it’s just “appname.modelname”. The reason is that Django is not using this to do a direct import; instead, it’s using an internal model-loading function which only wants the name of the app and the name of the model. Trying to do things like “appname.models.modelname” or “projectname.appname.models.modelname” in the AUTH_PROFILE_MODULE setting will cause Django to blow up with the dreaded “too many values to unpack” error, so make sure you’ve put “appname.modelname”, and nothing else, in the value of AUTH_PROFILE_MODULE.

If the OP had copied more of the traceback I would expect to see something like the one below which I was able to duplicate by adding “models” to my AUTH_PROFILE_MODULE setting.

TemplateSyntaxError at /

Caught an exception while rendering: too many values to unpack

Original Traceback (most recent call last):
  File "/home/brandon/Development/DJANGO_VERSIONS/Django-1.0/django/template/debug.py", line 71, in render_node
    result = node.render(context)
  File "/home/brandon/Development/DJANGO_VERSIONS/Django-1.0/django/template/debug.py", line 87, in render
    output = force_unicode(self.filter_expression.resolve(context))
  File "/home/brandon/Development/DJANGO_VERSIONS/Django-1.0/django/template/__init__.py", line 535, in resolve
    obj = self.var.resolve(context)
  File "/home/brandon/Development/DJANGO_VERSIONS/Django-1.0/django/template/__init__.py", line 676, in resolve
    value = self._resolve_lookup(context)
  File "/home/brandon/Development/DJANGO_VERSIONS/Django-1.0/django/template/__init__.py", line 711, in _resolve_lookup
    current = current()
  File "/home/brandon/Development/DJANGO_VERSIONS/Django-1.0/django/contrib/auth/models.py", line 291, in get_profile
    app_label, model_name = settings.AUTH_PROFILE_MODULE.split('.')
ValueError: too many values to unpack

This I think is one of the few cases where Django still has a bit of import magic that tends to cause confusion when a small error doesn’t throw the expected exception.

You can see at the end of the traceback that I posted how using anything other than the form “appname.modelname” for the AUTH_PROFILE_MODULE would cause the line “app_label, model_name = settings.AUTH_PROFILE_MODULE.split(‘.’)” to throw the “too many values to unpack” error.

I’m 99% sure that this was the original problem encountered here.


回答 3

get_profile()调用中某处很可能有错误。在您看来,在返回请求对象之前,请放置以下行:

request.user.get_profile()

它会引发错误,并为您提供更详细的追溯,然后您可以将其用于进一步的调试。

Most likely there is an error somewhere in the get_profile() call. In your view, before you return the request object, put this line:

request.user.get_profile()

It should raise the error, and give you a more detailed traceback, which you can then use to further debug.


回答 4

当我使用Jinja2作为模板时,这会发生在我身上。通过使用django_extensions中runserver_plus命令运行开发服务器可以解决此问题。

它使用werkzeug调试器,该调试器也要好得多,并且具有非常好的交互式调试控制台。在任何帧(在调用堆栈中)启动python shell时,它具有ajax的魔力,因此您可以进行调试。

This happens to me when I’m using Jinja2 for templates. The problem can be solved by running the development server using the runserver_plus command from django_extensions.

It uses the werkzeug debugger which also happens to be a lot better and has a very nice interactive debugging console. It does some ajax magic to launch a python shell at any frame (in the call stack) so you can debug.


声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。