步骤一:创建Django项目
django-admin startproject mysite
步骤二:创建项目中使用到的应用
cd mysite
python manage.py startapp index
python manage.py startapp search
python manage.py startapp user
python manage.py startapp asset
步骤三:创建出模板文件和静态资源文件目录
在项目mysite目录下,创建文件夹templates和static。其中templates下为每个项目应用创建一个存放模板文件的子目录,index, search, user, asset。static下可以细分为css, js, font, image等子类目录。
mkdir templates static
mkdir -p ./templates/index
mkdir -p ./templates/search
mkdir -p ./templates/user
mkdir -p ./templates/asset
mkdir -p ./static/css
mkdir -p ./static/js
mkdir -p ./static/font
mkdir -p ./static/image
步骤四:配置setting.py,增加新的项目应用
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'index',
'search',
'user',
'asset',
]
步骤五:配置setting.py,添加中间件LocaleMiddleware以支持本地化的语言偏好
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.locale.LocaleMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
步骤六:配置setting.py,设置模板路径和静态文件路径
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'templates'),
],
'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',
],
},
},
]
STATIC_URL = '/static/'
STATIC_DIR = os.path.join(BASE_DIR, "static")
STATICFILES_DIRS = (os.path.join(BASE_DIR, "static"),)
步骤七:配置setting.py,设置数据库连接信息
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': DB_DATABASE,
'USER': DB_USER,
'PASSWORD': DB_PASSWORD,
'HOST': DB_HOST,
'PORT': DB_PORT,
}
}
- 请自行将以上DB连接配置字段替换为实际取值
步骤八:配置项目的urls.py,配置URL地址信息
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('index.urls')),
path('search/', include('search.urls')),
path('user/', include('user.urls')),
path('asset/', include('asset.urls')),
]
至此,一个完整的Django项目已经具备了所有必要的配置内容,可以进入业务应用逻辑的开发工作了。
关于setting.py的更多高级配置
语言与时区
LANGUAGE_CODE = 'zh'
TIME_ZONE = 'Asia/Shanghai'
USE_I18N = True
USE_L10N = True
USE_TZ = True
配置自定义用户表MyUser
AUTH_USER_MODEL = 'user.MyUser'
Email config
EMAIL_HOST = 'smtp.163.com'
EMAIL_PORT = 25
EMAIL_HOST_USER = 'userabc@163.com'
EMAIL_HOST_PASSWORD = '123456'
EMAIL_USE_SSL = False
EMAIL_USE_TLS = False
EMAIL_SUBJECT_PREFIX = '[MySite] '