settings.py文件里的一些说明 中文备注
from pathlib import Path
# 项目根目录
BASE_DIR = Path(__file__).resolve().parent.parent
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = "django-insecure-8-)70*g*bj&5ttlmabbga3%l442r5jpte0_#o)^vigvk+n$k3&"
# 是否使用调试模式 False:生产模式 True:开发模式
DEBUG = True
# 被允许的主机列表或IP地址列表
# 上线后可以执行其他哪些服务器来访问我
ALLOWED_HOSTS = ["*"]
# 定义应用
INSTALLED_APPS = [
"django.contrib.admin",
"django.contrib.auth",
"django.contrib.contenttypes",
"django.contrib.sessions",
"django.contrib.messages",
"django.contrib.staticfiles",
# 自定义应用
]
# 定义中间件
MIDDLEWARE = [
"django.middleware.security.SecurityMiddleware",
"django.contrib.sessions.middleware.SessionMiddleware",
"django.middleware.common.CommonMiddleware",
"django.middleware.csrf.CsrfViewMiddleware",
"django.contrib.auth.middleware.AuthenticationMiddleware",
"django.contrib.messages.middleware.MessageMiddleware",
"django.middleware.clickjacking.XFrameOptionsMiddleware",
]
# 根路由
ROOT_URLCONF = "djtest.urls"
# 模版配置
TEMPLATES = [
{
"BACKEND": "django.template.backends.django.DjangoTemplates",
"DIRS": [],
"APP_DIRS": True,
"OPTIONS": {
"context_processors": [
"django.template.context_processors.debug",
"django.template.context_processors.request",
"django.contrib.auth.context_processors.auth",
"django.contrib.messages.context_processors.messages",
],
},
},
]
# WSGI目录配置
WSGI_APPLICATION = "djtest.wsgi.application"
# Database
# https://docs.djangoproject.com/en/4.2/ref/settings/#databases
DATABASES = {
"default": {
"ENGINE": "django.db.backends.sqlite3",
"NAME": BASE_DIR / "db.sqlite3",
}
}
# Password validation
# https://docs.djangoproject.com/en/4.2/ref/settings/#auth-password-validators
# 密码验证
AUTH_PASSWORD_VALIDATORS = [
{
"NAME": "django.contrib.auth.password_validation.UserAttributeSimilarityValidator",
},
{
"NAME": "django.contrib.auth.password_validation.MinimumLengthValidator",
},
{
"NAME": "django.contrib.auth.password_validation.CommonPasswordValidator",
},
{
"NAME": "django.contrib.auth.password_validation.NumericPasswordValidator",
},
]
# Internationalization
# https://docs.djangoproject.com/en/4.2/topics/i18n/
LANGUAGE_CODE = "en-us"
TIME_ZONE = "UTC"
USE_I18N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/4.2/howto/static-files/
# 静态文件
STATIC_URL = "static/"
# Default primary key field type
# https://docs.djangoproject.com/en/4.2/ref/settings/#default-auto-field
# 默认的主键字段类型
DEFAULT_AUTO_FIELD = "django.db.models.BigAutoField"
启动服务 默认IP和端口 127.0.0.1:8000
python manage.py runserver
如果想要局域网内其他电脑访问可以修改IP和端口
python manage.py runserver 0.0.0.0:8888
这里必须改成*
# 被允许的主机列表或IP地址列表
# 上线后可以执行其他哪些服务器来访问我
ALLOWED_HOSTS = ["*"]
数据迁移
迁移的概念:就是将模型映射到数据库的过程
生成迁移文件:
python manage.py makemigrations
执行迁移:
python manage.py migrate
执行完以上2句代码后
本地的db.sqlite3里面的文件增加了很多表格
6.创建APP(可以修改自己定义的APP名称)
python manage.py startapp APP
在models.py里可以添加模型层数据类型,后期可以通过数据迁移到数据库
views.py是定义url的相应函数,视图函数。
在使用应用前要先配置到项目中,在settings.py中将应用添加到INSTALLED_APPS选项中