Django 配置文件
settings.py
詳解
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
python中 __file__
這個(gè)變量可以獲取到當(dāng)前文件(包含這個(gè)代碼的文件)的路徑。os.path.dirname(__file__)
得到文件所在目錄黑忱,再加上一層os.path.dirname()就是目錄的上一級(jí)宴抚,BASE_DIR 即為 項(xiàng)目 所在目錄勒魔。之后與目錄有關(guān)的變量會(huì)用它,這樣使得移植性更強(qiáng)菇曲。
DEBUG = True
DEBUG=True 時(shí)冠绢,如果出現(xiàn) bug 便于我們看見(jiàn)問(wèn)題所在,但是部署時(shí)最好不要讓用戶看見(jiàn)bug的詳情常潮,可能一些不懷好心的人攻擊網(wǎng)站弟胀,造成不必要的麻煩.
ALLOWED_HOSTS = ['www.xxx.com','192.168.1.11'] #可以設(shè)置 ip 和 域名
ALLOWED_HOSTS 允許你設(shè)置哪些域名可以訪問(wèn),即使在 Apache 或 Nginx 等中綁定了喊式,這里不允許的話孵户,也是不能訪問(wèn)的。當(dāng) DEBUG=False 時(shí)岔留,這個(gè)為必填項(xiàng)夏哭,如果不想輸入,可以用 ALLOW_HOSTS = ['*'] 來(lái)允許所有的献联。
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'test_django' , # 新應(yīng)用在后面追加
]
注冊(cè)應(yīng)用竖配,INSTALLED_APPS注冊(cè)應(yīng)用是為了和models.py里的模型/數(shù)據(jù)庫(kù)交互使用的,不注冊(cè)的話正常訪問(wèn)的是view,只要不和models.py有關(guān)聯(lián),都可以正常訪問(wèn)沒(méi)有影響,但是為了之后交互不出錯(cuò),最好寫新應(yīng)用時(shí)直接注冊(cè)好。
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'templates')]
# 'DIRS': [os.path.join(BASE_DIR, 'templates2')] 修改 模版存放位置
},
]
模版文件存放地址
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
數(shù)據(jù)庫(kù)配置
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
admin 后臺(tái)支持的語(yǔ)言,其中 zh-Hans是簡(jiǎn)體中文 zh-Hant是繁體中文,所以更改
LANGUAGE_CODE = 'zh-Hans'
TIME_ZONE = 'Asia/Shanghai'
USE_I18N = True
USE_L10N = True
USE_TZ = False
Django 數(shù)據(jù)庫(kù)默認(rèn) 配置(在 project 包下
settings.py
文件中)
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
mysql 數(shù)據(jù)庫(kù)配置
- 安裝 python 3.x 支持 pyMySql
pip install pymysql
- 在 project 包下
__init__.py
文件中寫入代碼
import pymysql
pymysql.install_as_MySQLdb()
- 在 project 包下
settings.py
文件中酱固,通過(guò) DATABASES 選項(xiàng)進(jìn)行數(shù)據(jù)庫(kù)配置
- mysql 數(shù)據(jù)庫(kù)配置:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql', #數(shù)據(jù)庫(kù)引擎
'NAME': 'db_name', # 數(shù)據(jù)庫(kù) 名稱
'USER':'root' # 數(shù)據(jù)庫(kù)用戶
'PASSWORD':'root' # 數(shù)據(jù)庫(kù)密碼
'HOST':'localhost' # 數(shù)據(jù)庫(kù)IP
'PORT':'3306' # 數(shù)據(jù)庫(kù)端口
}
}
postgresql 數(shù)據(jù)庫(kù)配置
- 安裝 psycopg2 實(shí)現(xiàn)對(duì)PostgreSQL數(shù)據(jù)庫(kù)的操作
pip install psycopg2
- 在 project 包下
settings.py
文件中械念,通過(guò) DATABASES 選項(xiàng)進(jìn)行數(shù)據(jù)庫(kù)配置
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'db_name', # 數(shù)據(jù)庫(kù)名字(需要先創(chuàng)建)
'USER': 'postgres', # 登錄用戶名
'PASSWORD': '123456', # 密碼
'HOST': '', # 數(shù)據(jù)庫(kù)IP地址,留空默認(rèn)為localhost
'PORT': '5432', # 端口
}
}