A, Django MySQL connection
1. Create a database ( note that set the character encoding data)
Because Django comes orm is data_first type of ORM, before using the database must be created
create database db default character set utf8 collate utf8_general_ci;
2, settings.py project file modification provided in connection MySQL database (the Django sqllite database is used by default)
DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME':'dbname', 'USER': 'xxx', 'PASSWORD': 'xxx', 'HOST': 'localhost', 'PORT': '3306', } }
3, __init__py file modify project settings to connect to MySQL's default way Django
import pymysql
pymysql.install_as_MySQLdb()
At this time run the program, if error: django.core.exceptions.ImproperlyConfigured: the mysqlclient 1.3.13 or newer IS required; you have have 0.9.3.
Solution:
1: django down to 2.1.4 version (version use Django2.2 This problem occurs, pro-test available)
2: Go to the next python installation directory: . . / Site-packages / django / db / backends / mysql base.py the file, comment out the following sections (lines 35-36):
if version < (1, 3, 3): raise ImproperlyConfigured("mysqlclient 1.3.3 or newer is required; you have %s" % Database.__version__)
At this point still being given, the following information is given: AttributeError: 'STR' Object attribute has NO 'decode
Find operations.py file (146 lines), the decode changed to encode (146 lines):
if query is not None:
query = query.decode(errors=‘replace‘)
return query
改为
if query is not None:
query = query.encode(errors=‘replace‘)
return query
4, create app in terminal
python manage.py startapp app01
5, models.py within the app to create class
class UserInfo(models.Model): nid = models.BigAutoField(primary_key=True) username = models.CharField(max_length=32) password = models.CharField(max_length=64)
6, setting.py registered app
INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'app01', #末尾添加 ]
7, create a data table
Terminal run:
python manage.py makemigrations
python manage.py migrate
Two, modles.py create a table