我正在使用带有Python 2.7的Django 1.7.1,当我尝试将带有急性重音(á,é等)的西班牙语字符传递给我的模板时,整个字符串不会出现在浏览器中(或在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>
浏览器显示空的<h1> </h1>
标记
解决
我按# -*- coding: utf-8 -*-
更改# -*- coding: iso-8859-15 -*-
并将'country': u'Perú'
代替'country': 'Perú'
标签
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
答案 0 :(得分:1)
你的问题是render_to_response
的第二个参数是作为上下文传递的字典,但是你直接在上下文中传递。
您可以通过以下两种方式解决问题;
推荐的解决方法是使用render
,如下所示:
def main_page(request):
return render(request, 'index.html', {'country': u'Perú'})
如果您想使用render_to_response
,则需要限定第二个参数:
return render_to_response('index.html',
context_instance=RequestContext(request,
{'country': u'Perú'}))