问题描述
我要在Django中实现评论功能,在models.py中添加了Comment模型,代码如下:
class Comment(models.Model):
article = models.ForeignKey(ArticlePost, related_name='comments')
commentator = models.CharField(max_length=90)
body = models.TextField() # 记录评论内容的字段
created = models.DateTimeField(auto_now_add=True)
在前端页面(其余代码省略),我在评论框中添加了一个的表情,如下图所示:
点击发评论按钮后,结果出错了,如下图所示:
网上一番搜寻后(参考http://blog.manbolo.com/2014/03/31/using-emojis-in-django-model-fields),原来是MySQL(没错,我的后端数据库用的是MySQL) 的 utf8 编码规定了最多只能有 3 个字节,而表情符号的 unicode 已经超过了 3 个字节,因此 MySQL 的 utf8 无法识别与存储 emoji。
解决办法
1.进入mysql,输入如下命令SHOW VARIABLES WHERE Variable_name LIKE 'character\_set\_%' OR Variable_name LIKE 'collation%';
,结果如下:
+--------------------------+-----------------+
| Variable_name | Value |
|--------------------------+-----------------|
| character_set_client | utf8 |
| character_set_connection | utf8 |
| character_set_database | utf8 |
| character_set_filesystem | binary |
| character_set_results | utf8 |
| character_set_server | utf8 |
| character_set_system | utf8 |
| collation_connection | utf8_general_ci |
| collation_database | utf8_general_ci |
| collation_server | utf8_general_ci |
+--------------------------+-----------------+
2.更改数据库,表的字符集属性,以使用utf8mb4,而不是utf8,依次键入如下两条命令:
ALTER DATABASE blog_shizhan CHARACTER SET = utf8mb4 COLLATE utf8mb4_unicode_ci;
(blog_shizhan是数据库名称)
ALTER TABLE article_comment CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
(article_comment是数据表名称)
此时,再次输入命令SHOW VARIABLES WHERE Variable_name LIKE 'character\_set\_%' OR Variable_name LIKE 'collation%';
,结果如下:
+--------------------------+--------------------+
| Variable_name | Value |
|--------------------------+--------------------|
| character_set_client | utf8 |
| character_set_connection | utf8 |
| character_set_database | utf8mb4 |
| character_set_filesystem | binary |
| character_set_results | utf8 |
| character_set_server | utf8 |
| character_set_system | utf8 |
| collation_connection | utf8_general_ci |
| collation_database | utf8mb4_unicode_ci |
| collation_server | utf8_general_ci |
+--------------------------+--------------------+
3.更改Django中settings.py的数据库配置,添加一行代码'OPTIONS': {'charset': 'utf8mb4'}
,如下所示:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'blog_shizhan',
'USER': 'XXXX',
'PASSWORD': 'XXXX',
'HOST': '',
'PORT': '',
'OPTIONS': {'charset': 'utf8mb4'}, # 添加此行代码
}
}
自此,修改步骤完成,再次点击发评论按钮后,可以成功的发布表情符号了。