Django-(1366," Invalid string value:... error

Django-(1366," Invalid string value:... error

问题描述:

当我尝试通过django管理员添加新记录时出现以下错误:

I am getting the following error when I try to add a new record via django admin:

OperationalError,位于/admin/competition/sport/add/ (1366,第1行的'object_repr'列的字符串值不正确:'\ xC4 \ x9F \ xC3 \ xBC'") 请求方法:POST 请求网址: http://127.0.0.1:8000/admin/competition/sport/添加/ Django版本:1.11.4 异常类型:OperationalError 异常值:
(1366,第1行的'object_repr'列的字符串值不正确:'\ xC4 \ x9F \ xC3 \ xBC'")

OperationalError at /admin/competition/sport/add/ (1366, "Incorrect string value: '\xC4\x9F\xC3\xBC' for column 'object_repr' at row 1") Request Method: POST Request URL: http://127.0.0.1:8000/admin/competition/sport/add/ Django Version: 1.11.4 Exception Type: OperationalError Exception Value:
(1366, "Incorrect string value: '\xC4\x9F\xC3\xBC' for column 'object_repr' at row 1")

这是模型:

class Sport(models.Model):
    is_team = models.BooleanField(_("Is Team"))
    name = models.CharField(_("Name"), max_length=200)

在我的settings.pymysql后端的选项:

'OPTIONS': {
        'charset': 'utf8mb4',
        'init_command': 'SET character_set_connection=utf8mb4;'
                        'SET collation_connection=utf8mb4_unicode_ci;'
                        "SET NAMES 'utf8mb4';"
                        "SET CHARACTER SET utf8mb4;"
    },

我已按照此处所述更新了所有表和列以使用utf8mb4

到目前为止,一切都没有.当我尝试使用mysql shell插入包含Unicode字符的记录时,我没有收到任何错误,但是django管理员给出了上面的错误.

Nothing has worked so far. I get no error when I try to insert a record that contains unicode characters using mysql shell, but the django admin gives the error above.

有趣的是,当我尝试手动插入记录时,以下代码可以完美地工作:

Interestingly the code below works perfectly when i try to insert a record manually:

Sport(is_team=True, name="ÜĞüiğÇÖ").save()

我终于找到了导致问题的原因. Django管理员默认记录每个操作(包括数据,在我的情况下是一些奇怪的unicode文本).事实证明,"django_admin_log"表具有"latin1"字符集,因此我只是将其转换为utf8:

I finally figured what causes the problem. Django admin logs every action by default (including the data, in my case it was some weird unicode text). It turns out 'django_admin_log' table has 'latin1' charset, so i simply converted it into utf8:

ALTER TABLE django_admin_log CONVERT TO CHARACTER SET utf8 COLLATE utf8_unicode_ci;

然后一切正常.

您必须修改django_admin_log字符集

You have to modify the django_admin_log character set

ALTER TABLE django_admin_log CHANGE object_repr object_repr VARCHAR(191) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;