一.配置虚拟环境
1.打开cmd,新建文件夹,并进入该文件夹
F:\>mkdir DjangoWeb
F:\>cd DjangoWeb
F:\DjangoWeb>
2.配置venv的命令,其中的env为虚拟环境的放置目录
F:\DjangoWeb>python -m venv env
3.输入env\Scripts\activate.bat,即可进入虚拟环境
F:\DjangoWeb>env\Scripts\activate.bat
(env) F:\DjangoWeb>
二.安装Django
pip install django==2.2
三.创建Django项目
django-admin startproject blog
四.运行Django服务器
(env) F:\DjangoWeb>cd blog
(env) F:\DjangoWeb\blog>python manage.py runserver
Watching for file changes with StatReloader
Performing system checks...
System check identified no issues (0 silenced).
You have 17 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): admin, auth, contenttypes, sessions.
Run 'python manage.py migrate' to apply them.
October 21, 2020 - 19:32:43
Django version 2.2, using settings 'blog.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CTRL-BREAK.
系统打印出这些信息,说明服务器启动成功了
五.使用mysql作为数据库
1. 安装mysql
(env) F:\DjangoWeb\blog>pip install mysqlclient
2.在settings.py修改默认数据库为mysql
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql', # 数据库引擎
'NAME': 'name', # 数据库名,先前创建的
'USER': 'root', # 用户名,可以自己创建用户
'PASSWORD': 'root', # 密码
'HOST': '127.0.0.1', # mysql服务所在的主机ip
'PORT': '3306', # mysql服务端口
}
}
3.在settings.py设置成中文,以及中国时区
# 把英文改为中文
LANGUAGE_CODE = 'zh-hans'
# 把国际时区改为中国时区
TIME_ZONE = 'Asia/Shanghai'
USE_I18N = True
USE_L10N = True
USE_TZ = False
4.在settings.py里设置STATIC_URL和MEDIA
STATIC_URL = '/static/'
STATICFILES_DIRS = [os.path.join(BASE_DIR, "static"), ]
# specify media root for user uploaded files,
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
5.在settings.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',
],
},
},
]
6.在urls.py配置静态文件路径
from django.conf.urls.static import static
from django.conf import settings
urlpatterns = [
path('admin/', admin.site.urls),
]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
7.重新启动
October 21, 2020 - 23:35:37
Django version 2.2, using settings 'blog.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CTRL-BREAK.
系统打印出这些信息,说明服务器启动成功了