强制转换为 Unicode:需要字符串或缓冲区,在 django admin 中渲染时发现 NoneType
Posted
技术标签:
【中文标题】强制转换为 Unicode:需要字符串或缓冲区,在 django admin 中渲染时发现 NoneType【英文标题】:coercing to Unicode: need string or buffer, NoneType found when rendering in django admin 【发布时间】:2013-04-16 15:34:46 【问题描述】:这个错误我很久没解决了:
渲染时捕获 TypeError:强制转换为 Unicode:需要字符串或缓冲区,找到 NoneType
当我尝试在我的一个模型上添加或修改时,它会在管理员中发生(显示正常)
这是模型:
class PS(models.Model):
id_ps = models.IntegerField(null=True)
client = models.ForeignKey(Client, null=True, blank=True)
nom_du_site = models.CharField(max_length=250)
rue_livraison = models.TextField(null=True)
complement_adresse = models.TextField(null=True)
code_postal_livraison = models.CharField(max_length=50, null=True)
ville_livraison = models.CharField(max_length=200, null=True)
pays_livraison = models.CharField(max_length=200, null=True)
distributeur = models.CharField(max_length=50, null=True)
tarif = models.CharField(max_length=250, null=True)
type_tarif = models.CharField(max_length=50, null=True)
type_installation = models.CharField(max_length=50, null=True)
def __unicode__(self):
return self.nom_du_site
@property
def pce(self):
try:
return PCE.objects.filter(ps=self)[0]
except IndexError:
return
#
def get_pce(self):
from pce.models import PCE
return PCE.objects.filter(ps=self).exclude(frequence='6M')
#
def get_pce_6m(self):
from pce.models import PCE
return PCE.objects.filter(ps=self,frequence='6M')
知道我在这里做错了什么吗?
追溯:
Environment:
Request Method: GET
Request URL: http://127.0.0.1:8026/admin/ps/ps/add/
Django Version: 1.2.5
Python Version: 2.7.2
Installed Applications:
['django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.admin',
'easy_thumbnails',
'django_extensions',
'contentadmin',
'south',
'sentry',
'sentry.client',
'indexer',
'file_uploader',
'paging',
'pagination',
'consommation',
'ps',
'pce',
'profil',
'analytics',
'document']
Installed Middleware:
('annoying.middlewares.StaticServe',
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'pagination.middleware.PaginationMiddleware')
Template error:
In template /usr/local/lib/python2.7/dist-packages/django/contrib/admin/templates/admin/includes/fieldset.html, error at line 19
Caught TypeError while rendering: coercing to Unicode: need string or buffer, NoneType found
9 : % for field in line %
10 : <div% if not line.fields|length_is:'1' % class="field-box% if not field.is_readonly and field.errors % errors% endif %"% endif %>
11 : % if not line.fields|length_is:'1' and not field.is_readonly % field.errors % endif %
12 : % if field.is_checkbox %
13 : field.field field.label_tag
14 : % else %
15 : field.label_tag
16 : % if field.is_readonly %
17 : <p> field.contents </p>
18 : % else %
19 : field.field
20 : % endif %
21 : % endif %
22 : % if field.field.field.help_text %
23 : <p class="help"> field.field.field.help_text|safe </p>
24 : % endif %
25 : </div>
26 : % endfor %
27 : </div>
28 : % endfor %
29 : </fieldset>
Traceback:
File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py" in get_response
100. response = callback(request, *callback_args, **callback_kwargs)
File "/usr/local/lib/python2.7/dist-packages/django/contrib/admin/options.py" in wrapper
288. return self.admin_site.admin_view(view)(*args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/django/utils/decorators.py" in _wrapped_view
76. response = view_func(request, *args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/django/views/decorators/cache.py" in _wrapped_view_func
78. response = view_func(request, *args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/django/contrib/admin/sites.py" in inner
190. return view(request, *args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/django/utils/decorators.py" in _wrapper
21. return decorator(bound_func)(*args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/django/utils/decorators.py" in _wrapped_view
76. response = view_func(request, *args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/django/utils/decorators.py" in bound_func
17. return func(self, *args2, **kwargs2)
File "/usr/local/lib/python2.7/dist-packages/django/db/transaction.py" in _commit_on_success
299. res = func(*args, **kw)
File "/usr/local/lib/python2.7/dist-packages/django/contrib/admin/options.py" in add_view
909. return self.render_change_form(request, context, form_url=form_url, add=True)
File "/usr/local/lib/python2.7/dist-packages/django/contrib/admin/options.py" in render_change_form
692. ], context, context_instance=context_instance)
File "/usr/local/lib/python2.7/dist-packages/django/shortcuts/__init__.py" in render_to_response
20. return HttpResponse(loader.render_to_string(*args, **kwargs), **httpresponse_kwargs)
File "/usr/local/lib/python2.7/dist-packages/django/template/loader.py" in render_to_string
186. return t.render(context_instance)
File "/usr/local/lib/python2.7/dist-packages/django/template/__init__.py" in render
173. return self._render(context)
File "/usr/local/lib/python2.7/dist-packages/django/template/__init__.py" in _render
167. return self.nodelist.render(context)
File "/usr/local/lib/python2.7/dist-packages/django/template/__init__.py" in render
796. bits.append(self.render_node(node, context))
File "/usr/local/lib/python2.7/dist-packages/django/template/debug.py" in render_node
72. result = node.render(context)
File "/usr/local/lib/python2.7/dist-packages/django/template/loader_tags.py" in render
125. return compiled_parent._render(context)
File "/usr/local/lib/python2.7/dist-packages/django/template/__init__.py" in _render
167. return self.nodelist.render(context)
File "/usr/local/lib/python2.7/dist-packages/django/template/__init__.py" in render
796. bits.append(self.render_node(node, context))
File "/usr/local/lib/python2.7/dist-packages/django/template/debug.py" in render_node
72. result = node.render(context)
File "/usr/local/lib/python2.7/dist-packages/django/template/loader_tags.py" in render
125. return compiled_parent._render(context)
File "/usr/local/lib/python2.7/dist-packages/django/template/__init__.py" in _render
167. return self.nodelist.render(context)
File "/usr/local/lib/python2.7/dist-packages/django/template/__init__.py" in render
796. bits.append(self.render_node(node, context))
File "/usr/local/lib/python2.7/dist-packages/django/template/debug.py" in render_node
72. result = node.render(context)
File "/usr/local/lib/python2.7/dist-packages/django/template/loader_tags.py" in render
62. result = block.nodelist.render(context)
File "/usr/local/lib/python2.7/dist-packages/django/template/__init__.py" in render
796. bits.append(self.render_node(node, context))
File "/usr/local/lib/python2.7/dist-packages/django/template/debug.py" in render_node
72. result = node.render(context)
File "/usr/local/lib/python2.7/dist-packages/django/template/defaulttags.py" in render
174. nodelist.append(node.render(context))
File "/usr/local/lib/python2.7/dist-packages/django/template/loader_tags.py" in render
139. return self.template.render(context)
File "/usr/local/lib/python2.7/dist-packages/django/template/__init__.py" in render
173. return self._render(context)
File "/usr/local/lib/python2.7/dist-packages/django/template/__init__.py" in _render
167. return self.nodelist.render(context)
File "/usr/local/lib/python2.7/dist-packages/django/template/__init__.py" in render
796. bits.append(self.render_node(node, context))
File "/usr/local/lib/python2.7/dist-packages/django/template/debug.py" in render_node
72. result = node.render(context)
File "/usr/local/lib/python2.7/dist-packages/django/template/defaulttags.py" in render
174. nodelist.append(node.render(context))
File "/usr/local/lib/python2.7/dist-packages/django/template/defaulttags.py" in render
174. nodelist.append(node.render(context))
File "/usr/local/lib/python2.7/dist-packages/django/template/defaulttags.py" in render
260. return self.nodelist_false.render(context)
File "/usr/local/lib/python2.7/dist-packages/django/template/__init__.py" in render
796. bits.append(self.render_node(node, context))
File "/usr/local/lib/python2.7/dist-packages/django/template/debug.py" in render_node
72. result = node.render(context)
File "/usr/local/lib/python2.7/dist-packages/django/template/defaulttags.py" in render
260. return self.nodelist_false.render(context)
File "/usr/local/lib/python2.7/dist-packages/django/template/__init__.py" in render
796. bits.append(self.render_node(node, context))
File "/usr/local/lib/python2.7/dist-packages/django/template/debug.py" in render_node
72. result = node.render(context)
File "/usr/local/lib/python2.7/dist-packages/django/template/debug.py" in render
91. output = force_unicode(output)
File "/usr/local/lib/python2.7/dist-packages/django/utils/encoding.py" in force_unicode
66. s = unicode(s)
File "/usr/local/lib/python2.7/dist-packages/django/forms/forms.py" in __unicode__
408. return self.as_widget()
File "/usr/local/lib/python2.7/dist-packages/django/forms/forms.py" in as_widget
450. return widget.render(name, data, attrs=attrs)
File "/usr/local/lib/python2.7/dist-packages/django/contrib/admin/widgets.py" in render
247. output = [self.widget.render(name, value, *args, **kwargs)]
File "/usr/local/lib/python2.7/dist-packages/django/forms/widgets.py" in render
447. options = self.render_options(choices, [value])
File "/usr/local/lib/python2.7/dist-packages/django/forms/widgets.py" in render_options
464. for option_value, option_label in chain(self.choices, choices):
File "/usr/local/lib/python2.7/dist-packages/django/forms/models.py" in __iter__
898. yield self.choice(obj)
File "/usr/local/lib/python2.7/dist-packages/django/forms/models.py" in choice
904. return (self.field.prepare_value(obj), self.field.label_from_instance(obj))
File "/usr/local/lib/python2.7/dist-packages/django/forms/models.py" in label_from_instance
955. return smart_unicode(obj)
File "/usr/local/lib/python2.7/dist-packages/django/utils/encoding.py" in smart_unicode
39. return force_unicode(s, encoding, strings_only, errors)
File "/usr/local/lib/python2.7/dist-packages/django/utils/encoding.py" in force_unicode
66. s = unicode(s)
Exception Type: TemplateSyntaxError at /admin/ps/ps/add/
Exception Value: Caught TypeError while rendering: coercing to Unicode: need string or buffer, NoneType found
【问题讨论】:
为什么缺少from/import
和重复from/import
所有相同的模块?
我看到% for field in line %
,line
是什么?
@rednaw 它在模板中 /usr/local/lib/python2.7/dist-packages/django/contrib/admin/templates/admin/includes/fieldset.html 所以我也不知道跨度>
@KevinDTimm 那在哪里?我不明白你的意思对不起
你为什么还要return unicode(self.nom_du_site)
?为什么不只是return self.nom_du_site
?那一栏到底有什么?也许与此有关。
【参考方案1】:
首先,检查您通过 unicode 返回的内容是否为字符串。
如果不是字符串,可以改成这样的字符串(self.id是整数)
def __unicode__(self):
return '%s' % self.id
接下来,如果仍然无法正常工作,请重新启动您的 ./manage.py shell 以使更改生效,然后重试。它应该可以工作。
最好的问候
【讨论】:
没有。无论您通过__unicode__
返回什么,都必须是 unicode 对象,而不是字节串。使用unicode(self.id)
,或者,如果必须,使用u'%s' % self.id
。 (确实,在这种情况下答案会起作用,因为 id 总是一个整数,但答案应该给出正确的实现,而不是偶然发生的事情。)【参考方案2】:
当您有一个返回未输入字段的__unicode__
方法时会发生此错误。任何空白字段都是None
,Python 无法转换None
,所以会出现错误。
在您的情况下,问题很可能出在 PCE
模型的 __unicode__
方法上,特别是其返回的字段。
您可以通过返回默认值来防止这种情况:
def __unicode__(self):
return self.some_field or u'None'
【讨论】:
顺便说一下(对于那些可能从深夜睡眼惺忪的人),它也可能是由__unicode__
中的未返回任何内容 引起的。 :)
即使您的对象字段在更改页面上看起来不错,当相关字段之一 __unicode__
返回无时,您也可以拥有它!
或者在 python3 (Django 2.0) - def __str__(self): return unicode(self.some_field) or "" - 我有一些字段为 null 并且数据已经在填充数据中 - 所以我可以不要从管理员中删除它们-返回默认值就可以了...【参考方案3】:
当您在 __unicode__
方法中返回对象而不是字符串时,可能会发生此错误。例如:
class Author(models.Model):
. . .
name = models.CharField(...)
class Book(models.Model):
. . .
author = models.ForeignKey(Author, ...)
. . .
def __unicode__(self):
return self.author # <<<<<<<< this causes problems
为避免此错误,您可以将作者实例转换为 unicode:
class Book(models.Model):
. . .
def __unicode__(self):
return unicode(self.author) # <<<<<<<< this is OK
【讨论】:
【参考方案4】:在我的情况下,这是另外一回事:我要保存的对象首先应该有一个 id(例如,应该调用 save()),然后才能设置任何类型的关系。
【讨论】:
【参考方案5】:返回值 def __unicode __ 应该与相关模型(表)的返回值相似,以便在 django 管理面板中正确查看“some_field”。 您还可以使用:
def __str__(self):
return self.some_field
【讨论】:
【参考方案6】:用提供的函数替换之前的函数。最简单的解决方案是:
def __unicode__(self):
return unicode(self.nom_du_site)
【讨论】:
以上是关于强制转换为 Unicode:需要字符串或缓冲区,在 django admin 中渲染时发现 NoneType的主要内容,如果未能解决你的问题,请参考以下文章
TypeError:强制转换为 Unicode:需要字符串或缓冲区,找到字典 [关闭]
TypeError:强制转换为 Unicode:需要字符串或缓冲区,找到 datetime.timedelta
管理界面中的 Django auth.User:强制转换为 Unicode:需要字符串或缓冲区,找到用户