django 连接mysql出现不支持中文情况

_mysql.connection.query(self, query)
_mysql_exceptions.OperationalError: (1366, "Incorrect string value: '\\xE5\\xBC\\x82\\xE5\\xB8\\xB8…' for column 'title' at row 1")

 

主要原因在于新建数据库的时候没有选择UTF8字符集,默认的字符集是不支持中文的。

否则,要把所有表内所有字段的字符集全改为UTF8。

方法如下:

https://blog.csdn.net/ch717828/article/details/41357431

然而django还牵扯到一些其他数据库表,修改起来太麻烦,还是注意在新建数据库的时候选择UTF8字符集,更为方便。

因为要开发个考核系统,领导需求增加字段,在model里面增加字段,提示

You are trying to add a non-nullable field 'pj_leader' to posts without a default; we can't do that (the database needs something to populate existing rows).
Please select a fix:
1) Provide a one-off default now (will be set on all existing rows with a null value for this column)
2) Quit, and let me add a default in models.py
Select an option: exit
Please select a valid option: 2

虽然说是要提供默认值,其实原因应该不在此。初学,两个问题,还是重新建立表好了。

1、删了数据库,重新建立数据库,修改字符集UTF8。

2、删了django的migration文件夹

3、删除数据库中表django_mirgrations中app的那一行

4、重新建立数据库关联

python manage.py makemigrations
python manage.py migrate

(myprojectenv) root@mypc ~/myproject/myproject $ python manage.py makemigrations posts
Migrations for 'posts':
posts/migrations/0001_initial.py
– Create model Posts
(myprojectenv) root@mypc ~/myproject/myproject $ python manage.py migrate
Operations to perform:
Apply all migrations: admin, auth, contenttypes, posts, sessions
Running migrations:
Applying contenttypes.0001_initial… OK
Applying auth.0001_initial… OK
Applying admin.0001_initial… OK
Applying admin.0002_logentry_remove_auto_add… OK
Applying admin.0003_logentry_add_action_flag_choices… OK
Applying contenttypes.0002_remove_content_type_name… OK
Applying auth.0002_alter_permission_name_max_length… OK
Applying auth.0003_alter_user_email_max_length… OK
Applying auth.0004_alter_user_username_opts… OK
Applying auth.0005_alter_user_last_login_null… OK
Applying auth.0006_require_contenttypes_0002… OK
Applying auth.0007_alter_validators_add_error_messages… OK
Applying auth.0008_alter_user_username_max_length… OK
Applying auth.0009_alter_user_last_name_max_length… OK
Applying posts.0001_initial… OK
Applying sessions.0001_initial… OK

4、最后建立superuser

(myprojectenv) root@mypc ~/myproject/myproject $ python manage.py createsuperuser
Username (leave blank to use root):
Email address:
Password:
Password (again):
Superuser created successfully.
(myprojectenv) root@mypc ~/myproject/myproject $

5、启动服务( 如果用./manage.py runserver 127.0.0.1:8000,只能本机访问,其他电脑是无法访问的)

(myprojectenv) root@mypc ~/myproject/myproject $ ./manage.py runserver 192.168.50.69:8000
Performing system checks…

System check identified no issues (0 silenced).
October 31, 2018 – 15:14:45
Django version 2.1.2, using settings 'myproject.settings'
Starting development server at http://192.168.50.69:8000/
Quit the server with CONTROL-C.

Tagged on:

发表评论

电子邮件地址不会被公开。 必填项已用*标注

此站点使用Akismet来减少垃圾评论。了解我们如何处理您的评论数据