如何使用utf-8设置django和mysql [英] how to set django and mysql work with UTF-8
问题描述
我想将Django/mysql站点设置为与UTF-8一起使用.请指导我必须在django和mysql中进行的更改,以确保以下内容.
I want to set my Django/mysql site to work with UTF-8. Please guide me the changes I have to make in django and mysql to make sure the following things.
-
用户在表格中输入的数据将始终编码为UTF-8
User entered data in the forms will be always encoded as UTF-8
将数据作为utf-8存储在mysql中
Storing the data in mysql as utf-8
在模板中正确显示utf8编码的数据
Displaying utf8 encoded data in the template correctly
我还想知道转换为UTF-8编码是否会消除unicode解码错误,如下所示.
Also I want to know whether moving to UTF-8 encoding will remove unicode decode error like below.
UnicodeDecodeError:"ascii"编解码器无法解码位置55的字节0xc2:序数不在范围(128)中
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc2 in position 55: ordinal not in range(128)
非常感谢.
推荐答案
此处有一些建议:
1)创建数据库时使用utf8编码
1) use utf8 encoding when creating database
CREATE DATABASE <dbname> CHARACTER SET utf8;
2)在脚本的第一行或第二行中放置以下特殊注释:
2) place the following special comment in the first or second lines of your script:
# -*- coding: utf-8 -*-
3)在* .py文件中使用带u前缀的unicode字符串
3) Use unicode strings with u prefix in *.py files
unicodeString = u"hello Unicode world!"
4)在基本模板的部分中使用以下元标记:
4) Use follwing meta tag in section of your base template:
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
这篇关于如何使用utf-8设置django和mysql的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!