Django basics-create project APP and connect to MySQL database
I started learning Django on the way of learning python. Today I published this article to record Django's creation of project APP and connection to MYSQL database.
Django creates an APP project
the first method:
1. Create a project APP while creating a Django project
The second method: (a Django project has been created)
1. First create the project app, enter in the command line window below pycharm:
python manage.py startapp appname #appname是你想设置的app名称
Then it will generate a firstapp directory.
2. Then add your own APP in settings.py
Django connect to MySQL database
1. Since the ORM in Django cannot create a database, you must first create a database in MySQL by yourself
create database mysite #创建一个名为mysite的数据库
2. Then you need to add settings in settings.py to connect to the MySQL database
3. Use a third-party package to connect to the database. The default connection method in Django is MySQLdb. I use the pymysql package, so you need to set the way Django connects to MySQL in __init__.py (if there is no pymysql package, you can execute pip install in the command line window) pymysql to download the pymysql package)
4. Then you can create a data table in models.py in the app file
5. Then enter two commands in the python command line window
python manage.py makemigrations #用于保存models.py文件中的变更
The problem occurs: the
following error may be reported after input: (I encountered the thunder, skip if there is no such problem)
Solution:
Click the operations.py file in the blue link in the above picture, and change the decode of line 146 It can be solved by encode.
If there are no above problems, the command line window will display after success:
Then enter the second command
python manage.py migrate #将变更的内容翻译成SQL语句
After success, the command line will display:
6. MySQL Visual Database in Django
Click Database on the right side of pycharm, a small window appears, select MySQL
If the following conditions are displayed in the lower right corner, you need to download a driver, just click Download
After downloading the driver, fill in the information and click the Test Connection button below to test. If Successful appears, it means success, and then click ok in the lower right corner.
Just record this first!