設(shè)計(jì)django網(wǎng)站的翻頁功能(注意程序在不同.py文件中切換的邏輯)
1. 打開views.py
,添加如下:
def index(request):
+ context ={ # 模擬一個(gè)假的數(shù)據(jù)庫.models層相當(dāng)于一個(gè)數(shù)據(jù)庫的代理手形,把數(shù)據(jù)庫內(nèi)容映射到templates模版層中,
+ 'title': 'it is a new title', # 實(shí)現(xiàn)了同一頁面加載不同數(shù)據(jù)的功能
+ 'des': 'let me say something, ok,i need more word for the web',
+ 'tag': 'love'
+ }
return render(request, 'index.html',context)
上述添加一個(gè)context后 哩陕,最后render會(huì)將該段內(nèi)容渲染到網(wǎng)頁中
2. 網(wǎng)頁中更改對應(yīng)的代碼,templates下的index.html
更改前: <h2 class="post-title"> My Home </h2>
更改后: <h2 class="post-title">{{ title }}</h2> # {{ }} 套著瞻讽,就可以實(shí)現(xiàn)內(nèi)容的替代器腋,注意對比ruby
3. 更改連接數(shù)據(jù)庫設(shè)置
在最下方settings.py
添加:
from mongoengine import connect
connect ('website', host='127.0.0.1', port= 27017 )
4. 連接數(shù)據(jù)庫,models.py
這里先安裝 pip3 install mongoengine
,第一次要重啟pycharm
修改models.py
class ItemInfo(Document): # 類的命名方式赤兴,括號內(nèi)是它繼承的類队伟,面向?qū)ο? title = StringField()
url = StringField()
price = IntField() # 這里的命名必須對應(yīng)數(shù)據(jù)庫里的命名
look = StringField() # 而且腔稀,這里必須列出所有數(shù)據(jù)庫的key,否則報(bào)錯(cuò)提示某key 不存在
area = StringField()
cates = StringField()
pub_date = StringField()
meta = {'collection':'new_ganji1'} # 僅用于調(diào)用已存在的數(shù)據(jù)庫盆昙,這行就是告訴django,你的數(shù)據(jù)是從哪里來的焊虏,對應(yīng)哪個(gè)collection
for i in ItemInfo.objects[:1]:
print(i.title,i.url,i.price)
5. 修改views.py
def index(request):
item_info = ItemInfo.objects[:1] # 新增這條從數(shù)據(jù)庫調(diào)用數(shù)據(jù)了
context ={ # 模擬一個(gè)假的數(shù)據(jù)庫.models層相當(dāng)于一個(gè)數(shù)據(jù)庫的代理淡喜,把數(shù)據(jù)庫內(nèi)容映射到templates模版層中,
'title': item_info[0].title, # 這里修改了诵闭,對照數(shù)據(jù)庫炼团。
'url': item_info[0].url,
'price': item_info[0].price
}
return render(request, 'index.html',context) # 調(diào)用
重啟澎嚣,刷新,數(shù)據(jù)載入正常
翻頁鍵的設(shè)計(jì)
1. 繼續(xù)修改views.py
from django.core.paginator import Paginator # 最上方加上這句代碼
...............
def index(request):
limit = 4 # 一頁限制4條數(shù)據(jù),從數(shù)據(jù)庫中隨機(jī)放4條狗
item_info = ItemInfo.objects[:1] # 這里1表示顯示一條信息瘟芝,比如title易桃,一個(gè)小塊只能配一條狗
paginator = Paginator(item_info,limit)
page = request.GET.get('page',1) # 請求獲得一頁
loaded = paginator.page(page)
context ={ # 模擬一個(gè)假的數(shù)據(jù)庫.models層相當(dāng)于一個(gè)數(shù)據(jù)庫的代理,把數(shù)據(jù)庫內(nèi)容映射到templates模版層中锌俱,
'ItemInfo':loaded
}
return render(request, 'index.html',context) # 調(diào)用
2. 修改index.html
{% for i in ItemInfo %} # 大致用這樣的方法將內(nèi)部的顯示循環(huán)起來晤郑。把數(shù)據(jù)庫的數(shù)據(jù)調(diào)用起來
..........
<div class="post-description">
<p>
{{ i.title }}
</p>
.........
{% endfor %}
3. 設(shè)計(jì)翻頁鍵
最后,我們再添加這段代碼贸宏,在footer前添加造寝。
<div class="text text-right">
{% if ItemInfo.has_previous %}
<a href="?page={{ ItemInfo.previous_page_number }}"> < Pre </a>
{% endif %}
<span> {{ ItemInfo.number }} of {{ ItemInfo.paginator.num_pages }} </span>
{% if ItemInfo.has_next %}
<a href="?page={{ ItemInfo.next_page_number }}"> Next></a>
{% endif %}
</div>
實(shí)現(xiàn)了大致的翻頁功能