I眠寿、上傳圖片
在Django中上傳圖片包括兩種方式
1.在管理頁面admin中上傳圖片
2.自定義form表單中上傳圖片,上傳圖片后躬翁,將圖片存儲在服務器上,然后將圖片的路徑存儲在表中盯拱。
Ein.設計上傳
使用模型處理上傳文件:將屬性定義成models.ImageField類型
如果屬性類型為imageField需要安裝Pilow
pip install Pillow
打開 應用/models.py文件盒发,定義模型類PicTest例嘱。
class PicTest(models.Model):
pic = models.ImageField(upload_to='booktest/') #upload_to指定圖片保存的路徑
生成遷移,執(zhí)行遷移宁舰,然后在static目錄下創(chuàng)建media目錄拼卵,再創(chuàng)建應用名稱的目錄,此例為booktest蛮艰。
打開 項目/settings.py文件腋腮,設置圖片保存路徑。
因為圖片也屬于靜態(tài)文件壤蚜,所以保存到static目錄下即寡,需在settings.py內(nèi)添加。
MEDIA_ROOT=os.path.join(BASE_DIR,"static/media")
Zwei.在管理頁面admin中上傳圖片
打開 應用/admin.py文件袜刷,注冊PicTest聪富。
from django.contrib import admin
from booktest.models import *
admin.site.register(PicTest)
注冊管理員賬戶
python manage.py createsuperuser
運行服務器,輸入如下網(wǎng)址著蟹。
點擊PicTest 內(nèi)的+Add墩蔓,選擇文件,點擊Save萧豆。然后在media/booktest內(nèi)找到照片
Drei.自定義form表單中上傳圖片
(1) 打開 項目/views.py文件奸披,創(chuàng)建視圖pic_upload。
def pic_upload(request):
return render(request,'booktest/pic_upload.html')
(2) 打開 項目/urls.py文件炕横,配置url源内。
url(r'^pic_upload/$', views.pic_upload),
(3) 在templates/booktest/目錄下創(chuàng)建模板pic_upload.html。
在模板中定義上傳表單份殿,要求如下:
form的屬性enctype="multipart/form-data"
form的method為post
input的類型為file
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
{% csrf_token %}
<form action="/pic_handle/" method="post" enctype="multipart/form-data">
<input type="file" name="pic"><br>
<input type="submit" value="上傳">
</form>
</body>
</html>
(4)打開 項目/views.py文件膜钓,創(chuàng)建視圖pic_handle,用于接收表單保存圖片。
from django.conf import settings
from django.http import HttpResponse
def pic_handle(request):
"""
上傳圖片的處理
:param request:
:return:
"""
pic = request.FILES.get('pic')
# 返回圖片的名字
print(pic.name)
# 把圖片存入到 static文件夾下的media目錄
# 指定圖片的存儲路徑 static/media/ booktest
save_path = '{}/booktest/{}'.format(settings.MEDIA_ROOT,pic.name)
# 文件進行寫入
with open(save_path, 'wb') as f:
for content in pic.chunks():
f.write(content)
# 在數(shù)據(jù)庫中保存上傳記錄
PicTest.objects.create(pic= 'booktest/{}'.format(pic.name))
return HttpResponse('ok')
打開booktest/urls.py文件弊添,配置url敌蜂。
url(r'^pic_handle/$', views.pic_handle),
運行服務器,在瀏覽器中輸入如下網(wǎng)址:
http://127.0.0.1:8000/pic_upload/
Vier.顯示圖片
打開 應用/views.py文件沃疮,修改視圖pic_handle。
# 將最后幾行的語句改為如下:
# 在數(shù)據(jù)庫中保存上傳記錄
pic_Test = PicTest.objects.create(pic= 'booktest/{}'.format(pic.name))
context = {'pic': pic_Test}
return render(request, 'booktest/pic_show.html', context)
在templates/booktest/目錄下創(chuàng)建模板pic_show.html梅肤。
<body>
<img style="width: 300px; width: 200px" src="/static/media/{{ pic.pic}}" alt="圖片加載失敗">
</body
即可在上傳后跳轉(zhuǎn)到pic_show 并展示圖片
II司蔬、分頁
Django提供了數(shù)據(jù)分頁的類,這些類被定義在django/core/paginator.py中姨蝴。 類Paginator用于對列進行一頁n條數(shù)據(jù)的分頁運算俊啼。類Page用于表示第m頁的數(shù)據(jù)。
Ein.Paginator類實例對象
Paginator(列表,int):返回分頁對象左医,參數(shù)為列表數(shù)據(jù)授帕,每面數(shù)據(jù)的條數(shù)
1.屬性
count:返回對象總數(shù)同木。
num_pages:返回頁面總數(shù)。
page_range:返回頁碼列表跛十,從1開始彤路,例如[1, 2, 3, 4]。
2.方法
page(m):返回Page類實例對象芥映,表示第m頁的數(shù)據(jù)洲尊,下標以1開始。
Zwei.Page類實例對象
調(diào)用Paginator對象的page()方法返回Page對象屏轰,不需要手動構(gòu)造颊郎。
1.屬性
object_list:返回當前頁對象的列表。
number:返回當前是第幾頁霎苗,從1開始姆吭。
paginator:當前頁對應的Paginator對象。
2.方法
has_next():如果有下一頁返回True唁盏。
has_previous():如果有上一頁返回True内狸。
len():返回當前頁面對象的個數(shù).
Drei.一個實例
此處我們應用AreaInfo app做展示
首先在模板目錄areatest下創(chuàng)建page_test.html,然后返回views.py編寫視圖函數(shù)
from django.shortcuts import render
from apps.areatest.models import AreaInfo
# 導入分頁包
from django.core.paginator import Paginator
def page_test(request,pIndex):
# pIndex表示當前頁碼
# 查詢所有省份地區(qū)的信息
list1 = AreaInfo.objects.filter(aParent__isnull=True)
# 將所有地區(qū)的信息按照一頁十條的方式進行顯示
p = Paginator(list1,10)
if pIndex == "":
# 給他展示第一頁
pIndex = '1'
# 要把傳過來的pIndex轉(zhuǎn)化成int型
pIndex = int(pIndex)
# 獲取第number頁的內(nèi)容
list2 = p.page(pIndex)
# 獲取所有頁面信息
plist = p.page_range
return render(request,'areatest/page_test.html',{'list':list2,'pIndex':pIndex,'plist':plist})
在areatest/urls.py內(nèi)配置url
from django.conf.urls import url
from apps.areatest import views
urlpatterns = [
url(r'^/$', views.area, name='area'),
# 對所有頁碼進行匹配厘擂,并顯示對應頁碼pIndex頁面的內(nèi)容
url(r'^page(?P<pIndex>[0-9]*)/$', views.page_test),
]
在page_test.html頁面內(nèi)編寫頁面
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<p>顯示當前頁的地區(qū)信息</p><br>
<ul>
{% for area in list %}
<li>
{{ area.id }}------>{{ area.atitle }}
</li>
{% endfor %}
</ul>
<p>顯示頁碼信息</p><br>
{% for pindex in plist %}
{% if pIndex == pindex %}
{{ pindex }}
{% else %}
<a href="/page{{ pindex }}/">{{ pindex }}</a>
{% endif %}
{% endfor %}
</body>
</html>