python - Django 1.8 中的模板 ("..").render() 不允许数值

标签 python django-1.8

我已从 Django 1.6 迁移到 Django 1.8。这在 Django 1.6 中工作正常,但在 Django 1.8 中给了我预期的字符串或缓冲区异常。

这是我的代码:

html = Template('hi {{name}}').render(Context({'name': 12}))

这里的问题是'name':12。将其更改为 'name':'12' 效果很好。

最佳答案

查看回溯(如果包含在您的问题中,这将会很有帮助),异常是在 Django 的国际化/本地化代码中引发的。这是回溯的最后几行:

  File "/home/mhawke/virtualenvs/django_1.8/lib/python2.7/site-packages/django/utils/lru_cache.py", line 125, in wrapper
    result = user_function(*args, **kwds)
  File "/home/mhawke/virtualenvs/django_1.8/lib/python2.7/site-packages/django/utils/translation/trans_real.py", line 409, in check_for_language
    if not language_code_re.search(lang_code):
TypeError: expected string or buffer

That looks like a bug to me as I found that lang_codeis None and that is not accepted by re.search(). Or it might be an issue with my configuration.

You can explicitly disable localisation in the context by passing use_l10n=False to Context like this:

>>> html = Template('hi {{name}}').render(Context({'name': 12}, use_l10n=False))
>>> html
u'hi 12'

因此,只要您可以将 use_l10n 传递给 Context,您就有一个解决方法,尽管您可能无法更改代码,否则您可以使用以下命令修复字典像这样的东西:

d = {k: str(v) for k,v in {'name': 12}.items()}
html = Template('hi {{name}}').render(Context(d))

如果您无法更改代码,还可以通过更改模板以在 name< 上使用 escapesafe 过滤器来防止此错误变量:

>>> html = Template('hi {{name|escape}}').render(Context({'name': 12}))
>>> html
u'hi 12'

或者您可以使用safe(如果您知道该值安全):

>>> html = Template('hi {{name|safe}}').render(Context({'name': 12}))
>>> html
u'hi 12'

但是,当应用过滤器来解决另一个问题时,这两种感觉都是错误的,并且它可能会掩盖该问题,或者给 future 的模板作者带来困惑。

关于python - Django 1.8 中的模板 ("..").render() 不允许数值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29822078/

相关文章:

python-3.4 - ldap3 操作 : SEARCH seems to fail (search_filter syntax vs RFC4515)

python - 模块未找到错误: No module named 'admin'

python - Django 1.8 错误的 PyDev 错误

python - 对列表中的 2 和 2 元素执行操作

python - 将列表传递给类中的函数

python - 我的 Django if 语句无法正常工作

Django 1.8 迁移 : django_content_type does not exist

python - "not all arguments converted during string formatting"Python Django

python - Django 中的 "Master page"管理

python - 地理错误: GeocoderServiceError: HTTP Error 500: Internal Server Error using pandas apply function with str concat