我在pythonanywhere.com上托管的Django应用程序不支持utf-8编码。像'é'这样的字符会返回错误。
视图:
def result_view(request):
if request.method == 'POST':
search = request.POST.get('textfield').encode("utf-8")
print search
try:
try:
value = wikipedia.page(search)
title = value.title
url = value.url
print title
data = wikipedia.summary(search, sentences=10)
except wikipedia.exceptions.DisambiguationError as e:
data = e
title = search + " (Disambiguation)"
u = search.replace(" ", "_")
url = "https://en.wikipedia.org/wiki/" + u
except:
raise Http404()
return render(request, "search/result.html", {'title': title, 'url': url, 'data': data})
else:
return render(request, "search/result.html", {})
textfield
输入使用utf-8编码,在Django开发服务器中正常工作,但在我的pythonanywhere
服务器中返回404页面。
模板:
<form name="myform" method="POST" action="{% url 'result' %}">
<div class="form-group">
<div class="input-group">
{% csrf_token %}
<input type="text" class="form-control" name="textfield" placeholder="Search" required/>
<div class="input-group-addon">
<span class="glyphicon glyphicon-search"></span>
</div>
</div>
</div>
<button type="submit" class="btn btn-danger btn-lg ">Search</button>
</form>
答案 0 :(得分:1)
您必须允许Pythonanyhere使用的数据库(它应该是来自here的MySQL,但可以更改)使用编码utf-8,为此,只需启动MySQL控制台,然后运行以下命令(当然用数据库的名称替换databasename):
ALTER DATABASE databasename CHARACTER SET utf8 COLLATE utf8_general_ci;
然后,对于每个表运行:
ALTER TABLE tablename CHARACTER SET utf8 COLLATE utf8_general_ci;
Utf-8是用于在数据库中存储非拉丁字符(例如西里尔字母)的标准编码,然后您需要更改其字符集和整理设置,首先在您的数据库上,然后在每个表上。< / p>
如果您有许多表,则可以使用存储过程执行这些命令。