Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
513 views
in Technique[技术] by (71.8m points)

python - Django - (1366, "Incorrect string value:... error

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

OperationalError at /admin/competition/sport/add/ (1366, "Incorrect string value: 'xC4x9FxC3xBC' 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: 'xC4x9FxC3xBC' for column 'object_repr' at row 1")

Here is the model:

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

And options for mysql backend at my settings.py:

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

I have updated all of the tables and columns to use utf8mb4 as described here

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.

Edit:

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

Sport(is_team=True, name="ü?üi???").save()

EDIT 2:

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;

Then everything worked fine.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...