1 安装相关版本的django,这里,我以5.1.1为例子
pip3 install django==5.1.1
(.venv) D:\DjangoCode\MS>pip3 install django==5.1.1
Looking in indexes: https://pypi.tuna.tsinghua.edu.cn/simple
Collecting django==5.1.1
Using cached https://pypi.tuna.tsinghua.edu.cn/packages/ba/aa/b423e37e9ba5480d3fd1d187e3fdbd09f9f71b991468881a45413522ccd3/Django-5.1.1-py3-none-any.whl (8.2 MB)
Collecting asgiref<4,>=3.8.1 (from django==5.1.1)
Using cached https://pypi.tuna.tsinghua.edu.cn/packages/39/e3/893e8757be2612e6c266d9bb58ad2e3651524b5b40cf56761e985a28b13e/asgiref-3.8.1-py3-none-any.whl (23 kB)
Collecting sqlparse>=0.3.1 (from django==5.1.1)
Using cached https://pypi.tuna.tsinghua.edu.cn/packages/5d/a5/b2860373aa8de1e626b2bdfdd6df4355f0565b47e51f7d0c54fe70faf8fe/sqlparse-0.5.1-py3-none-any.whl (44 kB)
Collecting tzdata (from django==5.1.1)
Using cached https://pypi.tuna.tsinghua.edu.cn/packages/a6/ab/7e5f53c3b9d14972843a647d8d7a853969a58aecc7559cb3267302c94774/tzdata-2024.2-py2.py3-none-any.whl (346 kB)
Collecting typing-extensions>=4 (from asgiref<4,>=3.8.1->django==5.1.1)
Using cached https://pypi.tuna.tsinghua.edu.cn/packages/26/9f/ad63fc0248c5379346306f8668cda6e2e2e9c95e01216d2b8ffd9ff037d0/typing_extensions-4.12.2-py3-none-any.whl (37 kB)
Installing collected packages: tzdata, typing-extensions, sqlparse, asgiref, django
Successfully installed asgiref-3.8.1 django-5.1.1 sqlparse-0.5.1 typing-extensions-4.12.2 tzdata-2024.2
2 启动项目
django-admin startproject MS .
注意,上面必须要加个".",效果如下:
3 配置相关环境
点击"add configuration"-->左上角"+"-->django server-->更改"Name":MS-->点击右下角"fix" -->选择"django"-->勾选"enable django support"-->选择"root":D:\DjangoCodes\MS-->选择"settings":MS\settings.py
4 创建app,有两种方法,一种是手撸代码,一种是点击选择。
4.1 手撸
python manage.py startapp app01
4.2 点击选择
5 settings.py配置
5.1 数据库,因为我选择的是mysql,所以我需要进行如下配置:
5.1.1 安装pymysql:pip3 install pymysql
5.1.2 安装cryptography:pip3 install cryptography
5.1.3 在D:\DjangoCode\MS\MS__init__.py,配置数据库池子
import pymysql
pymysql.install_as_MySQLdb()
5.1.4 安装数据池:pip3 install django-db-connection-pool
5.1.5 安装pip3 install mysqlclient
5.1.6 修改settings.py里的"DATABASES"
DATABASES = {
"default": {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'demo_ms',
'USER': 'root',
'PASSWORD': 'root',
'HOST': '127.0.0.1',
'PORT': '3306',
'POOL_OPTIONS': {
"POOL_SIZE": 10,
"MAX_OVERFLOW": 10,
"RECYCLE": 3600,
"TIMEOUT": 60,
}
}
}
5.2 注册app,在settings.py里,找到"INSTALLED_APPS"
INSTALLED_APPS = [
"django.contrib.admin",
"django.contrib.auth",
"django.contrib.contenttypes",
"django.contrib.sessions",
"django.contrib.messages",
"django.contrib.staticfiles",
# 注册app01和app02
"app01.apps.App01Config",
"app02.apps.App02Config"
]
6 我们先启动看看,是否成功
7 编写测试类,看看数据库是否能正确连接
进入app01/models.py,写一个测试类
from django.db import models
# Create your models here.
class MsTestDemo(models.Model):
name = models.CharField(max_length=20)
age = models.IntegerField()
执行下面两条语句
manage.py@MS > makemigrations
manage.py@MS > migrate
可以看到,数据库是成功连接了。
以上就是Django的大概配置。