Template的配置以及搜索路径
在项目的根目录下的templates,后续所有的模板文件都放在这里面
'DIRS': [BASE_DIR / 'templates']
templates 在 每个已注册的app的子目录里,django建议的目录格式
'DIRS': []
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',
],
},
},
]
语言和时区
LANGUAGE_CODE = 'zh-hans'
TIME_ZONE = 'Asia/Shanghai'
USE_I18N = True
USE_TZ = True
STATIC_URL 静态文件路径
# 静态文件名
STATIC_URL = 'static/' # 静态文件在每个子应用
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'static'), #主项目目录下静态文件
os.path.join(BASE_DIR,"blog","statics"),#项目blog文件目录下的静态文件
)
使用MySQL配置
DATABASES = {
"default": {
"ENGINE": "django.db.backends.mysql",
"NAME": "book_42_01", # 提前建好DATAbase
"USER": "root",
"PASSWORD": "123456",
"HOST": "127.0.0.1",
"PORT": "3306",
}
}
安装好 mysqlclient 软件包,
pip install mysqlclient
执行
python.exe .\manage.py makemigrations
python.exe .\manage.py migrate
如果提示:django.db.utils.NotSupportedError: MySQL 8 or later is required (found 5.7.20).
修改base.py文件 ,注释掉版本检查
def init_connection_state(self):
"""Initialize the database connection settings."""
global RAN_DB_VERSION_CHECK
if self.alias not in RAN_DB_VERSION_CHECK:
# 注释掉
# self.check_database_version_supported()
RAN_DB_VERSION_CHECK.add(self.alias)
ALLOWED_HOSTS
修改访问地址,可以是IP,域名。列表的形式
ALLOWED_HOSTS = ['192.168.0.104', '127.0.0.1']
执行启动命令后,浏览器使用列表中的地址,都能访问。
python.exe .\manage.py runserver 0.0.0.0:8000
Django 域名访问,浏览器控制台提示错误 The Cross-Origin-Opener-Policy header has been ignored.....
ALLOWED_HOSTS = ['192.168.0.104', 'xxxxxx.vicp.fun', '127.0.0.1']
ALLOWED_HOSTS 增加了域名后,浏览器控制台会提示: The Cross-Origin-Opener-Policy header has been ignored, because the URL's origin was untrustworthy. It was defined either in the final response or a redirect. Please deliver the response using the HTTPS protocol. You can also use the 'localhost' origin instead. See https://www.w3.org/TR/powerful-features/#potentially-trustworthy-origin and https://html.spec.whatwg.org/#the-cross-origin-opener-policy-header. 需要个修改 global_setting.py
变更值为 SECURE_CROSS_ORIGIN_OPENER_POLICY 为 None.
SECURE_CROSS_ORIGIN_OPENER_POLICY = "same-origin"
SECURE_CROSS_ORIGIN_OPENER_POLICY = "None"
CSRF防护
Django默认开启了CSRF防护,会对 POST、PUT、PATCH、DELETE 请求方式进行CSRF防护验证,在测试时可以关闭CSRF防护机制,方法为在settings.py文件中注释掉CSRF中间件,如:
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',
]
配置 inclusion_tag
报错信息:
raise TemplateSyntaxError( django.template.exceptions.TemplateSyntaxError: 'project_tag' is not a r
解决方法:
在settings中添加