【问题标题】:Words with Unicode characters in them don't appear in HTML output包含 Unicode 字符的单词不会出现在 HTML 输出中
【发布时间】:2015-02-17 04:23:38
【问题描述】:

我将 Django 1.7.1 与 Python 2.7 一起使用,当我尝试将西班牙字符(如 ñ)或带有重音符号(á、é 等)的元音传递给我的模板时,整个字符串不会出现在浏览器中(或在 HTML 中)。我已经尝试了立竿见影的解决办法,就是把

# -*- coding: utf-8 -*-

在我的views.py 中也放

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

在我的模板中,但字符仍然没有出现。值得一提的是,网页加载没有错误,只有带有西班牙语单词的字符串没有出现。

编辑 1

我的views.py 文件看起来像

# -*- coding: utf-8 -*-
from django.shortcuts import render
from django.shortcuts import render_to_response
from django.template import RequestContext
# Create your views here.

def main_page(request):
    return render_to_response(
        'index.html', RequestContext(request,{
            'country':'Perú',
        })
    )

而我的模板index.html

<!DOCTYPE HTML>
<html>
<head>
<title>Webpage</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
</head>
<body>
    <h1> {{ country }}</h1>
</body>
</html>

浏览器显示一个空的&lt;h1&gt; &lt;/h1&gt;标签

已解决

我将# -*- coding: utf-8 -*- 更改为# -*- coding: iso-8859-15 -*- 并将'country': u'Perú' 替换为'country': 'Perú'

标签

&lt;meta http-equiv="Content-Type" content="text/html; charset=utf-8" /&gt;

在模板中不需要

【问题讨论】:

  • Django 通常非常擅长处理 Unicode。我自己真的没有时间深入研究这个问题,但是要添加到您的问题的一件事是-您究竟是如何将非 ascii 字符传递给模板的?如果你给它们提供 Python Unicode 字符串,Django 模板应该可以正常工作。我想我记得它也接受 utf-8 字节串并检测差异,但我不太确定。
  • 您可以添加自己的解决方案作为答案并接受它,以便将来遇到相同问题的访问者更容易找到。

标签: python django utf-8


【解决方案1】:

您的问题是 render_to_response 的第二个参数是作为上下文传递的字典,但您直接在上下文中传递。

您可以通过两种方式解决此问题;

  1. 建议的解决方法是只使用render,如下所示:

    def main_page(request):
        return render(request, 'index.html', {'country': u'Perú'})
    
  2. 如果你想使用render_to_response,你需要限定第二个参数:

    return render_to_response('index.html',
                              context_instance=RequestContext(request,
                                                             {'country': u'Perú'}))
    

【讨论】:

  • 嗨,谢谢你的回答,不幸的是我在这两种情况下都得到了错误(unicode错误)'utf8'编解码器无法解码位置0的字节0xfa:无效的起始字节(views.py,行15)
  • 您使用的是哪个文本编辑器?您确定文件views.py 实际存储为utf-8 吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-06-12
  • 2018-04-19
  • 2011-03-10
  • 1970-01-01
  • 2012-04-17
  • 1970-01-01
相关资源
最近更新 更多