django項目開發(fā)的流程:
1.創(chuàng)建django的項目
2.創(chuàng)建應(yīng)用
3.在setting.py 添加應(yīng)用
4.創(chuàng)建模型類
5.在setting.py 設(shè)置DATABASE
6.項目__init__.py設(shè)置pymysql的設(shè)置
7.生成遷移文件
8.執(zhí)行遷移
9.創(chuàng)建templates文件夾,模版的文件夾
10.在setting.py 設(shè)置模版的路徑
在TEMPLATES=[]中膊畴,將‘DIRS’:[]添加
'DIRS': [os.path.join(BASE_DIR,'template')],——拼接路徑
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
__file__:當(dāng)前的文件
os.path:模塊,對路徑操作
abspath():返回一個絕對路徑
D:\edu\python1802\20180503\code\demo0802_02\demo0802_01\ settings.py
dirname() :獲取目錄部分
D:\edu\python1802\20180503\code\demo0802_02\demo0802_01
dirname(‘D:\edu\python1802\20180503\code\demo0802_02\demo0802_01’)
結(jié)果:D:\edu\python1802\20180503\code\demo0802_02
BASE_DIR:項目根目錄
join(dir1,dir2) 合并成一個新的目錄
11.按照應(yīng)用,在templates目錄下創(chuàng)建子目錄
在templates下創(chuàng)建子目錄,目錄名為應(yīng)用名
12.創(chuàng)建模版文件(html)
創(chuàng)建html文件
已項目為例:創(chuàng)建兩個html膳凝,一個為index.html,一個為details.html
index.html
<body>
<h1>圖書列表</h1>
<ul>
{% for book in booklist %}
<li>
<a href="details/{{ book.id }}">{{ book.btitle }}</a>
</li>
{% endfor %}
</ul>
</body>
details.html
<body>
<h1>{{ book.btitle }}</h1>
<ul>
<!--book.heroinfo_set.all是求出所有英雄的信息-->
{% for hero in book.heroinfo_set.all %}
<li>{{ hero.hname}}----{{hero.hcentont}}</li>
{% endfor %}
</ul>
</body>
13.定義視圖函數(shù),處理客戶端的請求
a.查詢數(shù)據(jù)
b.加載模版
c.定義要插入上下文的字典數(shù)據(jù)
d.把數(shù)據(jù)插入模版麦轰,把渲染內(nèi)容返回
在views.py文件定義函數(shù)
from django.shortcuts import render
from booktest.models import BookInfo
from django.template import loader
from django.http import HttpResponse
# Create your views here.
# 定義的函數(shù)必須要有一個參數(shù)request
# 加載首頁
def index(request):
# 1.獲取圖書列表中所有的記錄
booklist = BookInfo.objects.all()
# 2.加載模板
template = loader.get_template('booktest/index.html')
#3.定義要插入上下文的字典數(shù)據(jù)
context = {'booklist':booklist}
#4.把數(shù)據(jù)插入模板,把渲染內(nèi)容返回
return HttpResponse(template.render(context))
# 加載圖書的詳細信息
def details(request,id):
# 1.查詢只定的圖書
book = BookInfo.objects.get(id=id)
# 2.加載模板
template = loader.get_template('booktest/details.html')
# 3.定義要插入上下文的字典數(shù)據(jù)
context = {'book': book}
# 4.把數(shù)據(jù)插入模板,把渲染內(nèi)容返回
return HttpResponse(template.render(context))
14.urlconf的定義
首先款侵,打開urls.py文件
from django.contrib import admin
from django.urls import path
from django.conf.urls import url
from django.conf.urls import include
urlpatterns = [
path('admin/', admin.site.urls),
url('^',include('booktest.urls')),
]
先到這個文件匹配正則驯嘱,booktest是應(yīng)用名,然后再去booktest下面的urls找喳坠,所以需要在booktest下創(chuàng)建一個urls.py文件
打開應(yīng)用名下面的urls.py文件修改
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$',views.index),
url(r'^details/(\d+)/$',views.details)
]
r'^details/(\d+)/$'匹配是以details開頭,然后以數(shù)字結(jié)尾茂蚓,因為這個項目最后是id壕鹉,所以就是數(shù)字