项目准备
1.创建项目(虚拟环境中自己指定目录)
django-admin startproject BookManager
2.创建应用
python manager.py startapp Book
3.python解释器:(Pycharm)
# 进入指定虚拟环境
which python
# python2
/home/python/.virtualenvs/py_django/bin/python
# python3
/home/python/.virtualenvs/py3_django/bin/python
4.安装应用(BookManager/settings.py)
INSTALLED_APPS=(
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'Book',#安装应用
)
5.本地化
LANGUAGE_CODE = 'zh-Hans'
TIME_ZONE = 'Asia/Shanghai'
6.模板路径
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',
],
},
},
]
并且在应用同级目录下,创建templates模板文件夹
7.项目中匹配urls
正则 : 路径只要不是admin/就算匹配成功。并包含到应用中的urls.py
BookManger/urs.py
urlpatterns = [
url(r'^admin/', include(admin.site.urls)),
# 路径只要不是'admin/'就算匹配成功。并包含到应用Book中的urls.py
url(r'^', include('Book.urls'))
]
8.应用中匹配urls.py
应用中创建urls.py
正则 : 路径中包含booklist/,就调用视图中对应的bookList函数
from django.conf.urls import url
import views
urlpatterns = [
# 路径中包含'booklist/',就调用视图中对应的bookList函数
url(r'^booklist/$', views.bookList)
]
9.准备视图(Book/views.py)
from django.http import HttpResponse
def bookList(request):
return HttpResponse('测试项目逻辑是否正确!')
10.开启服务器, 测试项目
进入项目文件中, 开启项目对应的服务器
python manage.py runserver
浏览器中输入网址
http://127.0.0.1:8000/booklist/