Django basics-create project APP and connect to MySQL database

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

Insert picture description here

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名称

Insert picture description here
Then it will generate a firstapp directory.

2. Then add your own APP in settings.py

Insert picture description here

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

Insert picture description here
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)

Insert picture description here
4. Then you can create a data table in models.py in the app file

Insert picture description here
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)
Insert picture description here
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:
Insert picture description here
Then enter the second command

python manage.py migrate        #将变更的内容翻译成SQL语句

After success, the command line will display:

Insert picture description here

6. MySQL Visual Database in Django

Click Database on the right side of pycharm, a small window appears, select MySQL

Insert picture description here
If the following conditions are displayed in the lower right corner, you need to download a driver, just click Download

Insert picture description here
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.Insert picture description here

Just record this first!

Guess you like

Origin blog.csdn.net/weixin_46791942/article/details/108555415