当前位置: 首页 > 面试题库 >

强制转换为Unicode:需要字符串或缓冲区,在Django管理中渲染时找到NoneType

廉鸿运
2023-03-14
问题内容

我已经有很长时间了,但是无法解决这个错误:

渲染时捕获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

问题答案:

当您使用的__unicode__方法是返回未输入的字段时,会发生此错误。任何空白字段均为None,Python无法转换None,因此会出现错误。

在您的情况下,问题很可能与PCE模型的__unicode__方法有关,特别是模型返回的字段。

您可以通过返回默认值来防止这种情况:

def __unicode__(self):
   return self.some_field or u'None'


 类似资料:
  • 问题内容: 我正在尝试启动并运行数据解析脚本。就数据操作而言,它起作用。我想要做的是设置此功能,以便我可以通过一个命令输入多个用户定义的CSV。 例如 如果您有关于如何自动输出CSV命名任何意见,这样,如果,我会很感激这一点。 得到 为线 我的代码: 我不太了解该错误的原因。有人可以用外行的术语解释吗? 请记住,我是一个整体的编程/ python新手,并且基本上是一个人学习,因此,如果可能的话,您

  • 我做了一个在上面渲染天空盒和粒子的应用程序。我想添加一些效果,我需要使用帧缓冲区来渲染天空盒、粒子颜色、深度和位置以分离纹理。然后我想使用简单的着色器来使用这些纹理中的值并以适当的方式混合它们。我为纹理、帧缓冲区和屏幕四边形(渲染简单的矩形)编写了辅助类,但不幸的是——当我尝试使用它时没有任何渲染。 当绑定帧缓冲区被注释掉时,我的场景如下所示: 修改着色器表明深度和位置值计算正确。因此问题在于纹理

  • 问题内容: 我想使用node.js进行HTTP请求以从Web服务器加载一些文本。由于响应可能包含很多文本(有些兆字节),因此我想分别处理每个文本块。我可以使用以下代码来实现: 这似乎没有问题。但是我想支持HTTP压缩,所以我使用zlib: 这可以是像多字节字符的问题,其由两个字节组成:和。如果第一个字节被第一个块()覆盖,第二个字节被第二个块覆盖,则将在文本块的结尾/开头产生不正确的字符。如何避免

  • 问题内容: 我正在尝试将url参数传递给这样的django模板… 这是我的views.py文件中的调用行。persistConTemplate.html是我的模板的名称,request.GET是包含url参数的字典。 在模板中,我尝试使用像这样的参数之一… numItems是我在请求中这样发送的url参数之一… 当我尝试上面的for循环时,我得到这样的输出。 我期待并希望看到字图像印刷12次… 谁

  • 我有一个node.js readstream,它发出一个缓冲区,并使用toString()函数将缓冲区转换为字符串,之后,当我试图通过JSON.parse()函数将字符串转换为JSON时,它会抛出解析错误。 有没有最好的方法将缓冲区转换为字符串,然后将字符串转换为JSON? JSON字符串如下所示, [{“data1”:1487328824948,“encrypt”:false,“version”

  • 我正在使用JOGL,但这个问题一般适用于OpenGL。似乎存在类似的问题,但它们要么针对GLSL代码,要么与复制帧缓冲区的内容有关,要么是一般建议-使用帧缓冲区对象,而不是。 我正在做一些阴影映射。如何使用帧缓冲对象将深度通道直接渲染到纹理? 能否请你贴一段初始化纹理和帧缓冲对象的代码,以及渲染场景前初始化一切的代码? 目前,我使用<code>glCopyTexSubImage2D<code>。我