Django--在线相册管理系统(2)
目錄
1、創建模板頁
2、創建首頁
3、?添加錯誤提示頁面
4、增加相冊信息
4.1、編寫網頁部分
4.2、編寫后端部分
?5、查看相冊信息
5.1、編寫網頁部分
5.2、編寫后端代碼
6、修改相冊信息
6.1、編寫網頁部分
6.2、編寫后端部分
7、刪除相冊信息
7.1、編寫后端部分
8、附加:點擊圖片變大
8.1、編寫后端部分
上一篇主要是在編寫相冊管理系統前的鋪墊,不知道的友友們可以去我主頁上查看。
Django--在線相冊管理系統(1)_橙子哈哈哈~的博客-CSDN博客
1、創建模板頁
我們先在templates文件夾中右擊新建一個base的網頁文件
,用來做模板頁,編寫代碼:
<!--模板頁--> <h1>在線相冊信息管理系統</h1> <a href="{% url 'index' %}">放回首頁</a> | <a href="{% url 'look' 1 %}">瀏覽相冊信息</a> | <a href="{% url 'add' %}">發布相冊信息</a> <hr/>?a標簽里的為url:反向解析。
index為跳轉頁面,后面的數字為參數。
這樣的好處會比較靈活,當某一個url配置的地址發生變化時,頁面上使用反向解析生成地址的位置不需要發生變化。
url的反向解析
在urls.py中添加路徑:
path('',views.index,name="index"),path('look/<int:pIndex>',views.look,name="look"),path('add',views.add,name="add"),在views.py中添加功能:
def index(request):return render(request, "index.html") # 首頁def add(request):return render(request, "addAlbum.html") # 添加頁面2、創建首頁
還是在templates文件夾中創建一個index的網頁文件,編寫代碼:
<!DOCTYPE html> <html lang="en"> <head><meta charset="UTF-8"><title>首頁</title> </head> <body><center>{% include "base.html" %} <!--加載模板并以標簽內的參數渲染--><h1>首頁</h1></center> </body> </html>3、?添加錯誤提示頁面
為的就是當操作錯誤時,就有一個提示作用。
在templates文件夾中創建一個info的網頁文件,編寫代碼:
<!DOCTYPE html> <html lang="en"> <head><meta charset="UTF-8"><title>Title</title> </head> <body><center>{% include 'base.html' %}<!-- 提示錯誤 -->{% if info != null %}<h3> {{ info }} </h3>{% if status == 200 %}<a href="{% url 'look' 1 %}">放回瀏覽頁</a>{% elif status == 400 %}<a href="javascript:history.go(-1)">返回上一頁</a>{% endif %}<br/><br/>{% endif %}<!-- 上傳和修改后的圖片展示 -->{% if image != null %}<img src='/static/{{image}}' width="500" height="330"/>{% endif %}<!-- 瀏覽圖片 -->{% if imageLook != null %}<br/><a href="javascript:history.go(-1)">返回上一頁</a><br/><br/><img src='/static/{{ imageLook }}'/>{% endif %}</center> </body> </html>?這里用到了一些django標簽的使用,不會的建議去補習一下基礎知識,我就當大家都會這些標簽的使用,不然挺麻煩的。
內容都在上面,包括與后面內容相聯系的代碼,現在看不懂的話,看到后面再回頭看或許有新的體會。
4、增加相冊信息
增刪改查,就先從增開始吧。
4.1、編寫網頁部分
在templates文件夾中創建一個addAlbum的網頁文件,編寫代碼:
<!DOCTYPE html> <html lang="en"> <head><meta charset="UTF-8"><title>發布相冊信息</title><script>//當選擇圖片后,就會立即在下方顯示選中圖片function setImagePreview(avalue) {var docObj = document.getElementById("doc");var imgObjPreview = document.getElementById("preview");if (docObj.files && docObj.files[0]) {imgObjPreview.style.width = '500px';imgObjPreview.style.height = '330px';imgObjPreview.src = window.URL.createObjectURL(docObj.files[0]);}return true;}</script> </head> <body><center>{% include 'base.html' %}<h2>添加相冊信息</h2><form method="post" action="{% url 'addImage' %}" enctype="multipart/form-data">{% csrf_token %} <!--防止跨站攻擊的方法--><table width="400"><tr><td>標題:</td><td><input type="text" name="title"></td></tr><tr><td>圖片:</td><td><input type="file" name="pic" id="doc" onchange="setImagePreview(this)"/><br></td></tr></table><input type="submit" value="添加"> <input type="reset" value="重置"></form><br/><img width="500" height="330" id="preview"/></center> </body> </html>注意:
- 當Django在處理文件上傳的時候,文件數據被保存在request.FILES
- FILES中的每個鍵為<input type="file" name="" />中的name
- 注意:FILES只有在請求的方法為POST 且提交的<form>帶有enctype="multipart/form-data" 的情況下才會包含數據。
- 否則,FILES 將為一個空的類似于字典的對象
4.2、編寫后端部分
?在urls.py文件中加上一個路徑:
path('addImage',views.addImage,name="addImage"),在views.py文件中添加功能:
from PIL import Image from ablumapp.models import Albumdef addImage(request):try:# 網頁傳輸內容的解析就不多說了,不懂的可以去百度下相關內容fileTitle = request.POST['title']fileImage = request.FILES.get("pic", None)fileTtpe = fileImage.name.split('.').pop() # 獲得圖片的后綴名,知曉是什么類型if fileImage == None:content = {"info": "暫無上傳文件!","status":400}return render(request, "info.html", content) if fileTitle == '':content = {"info": "請輸入標題!","status":400}return render(request, "info.html", content)if fileTtpe.lower() != "jpg" and fileTtpe.lower() != "png" and fileTtpe.lower() != "jpeg":content = {"info": "請選擇圖片文件!","status":400}return render(request, "info.html", content)# 判斷標題是否與數據庫中重復mod = Album.objects # ablumapp.models下的Album類ulist = mod.filter(title=fileTitle)if len(ulist) == 0:filename = request.POST['title'] + "." + fileTtpe # 組合后的文件名# 之前創建的static文件夾起到用途了,就是用它來存放上傳的圖片Imagefile = open("./static/" + filename, "wb+") for chuck in fileImage.chunks():Imagefile.write(chuck) Imagefile.close()# 執行圖片縮放im = Image.open("./static/" + filename)im.thumbnail((75, 75))im.save("./static/small/s_" + filename, None) # 記得在static文件夾中創建一個small文件夾,用來存放縮放后的圖片。# 添加記錄ob = Album()ob.title = fileTitleob.type = fileTtpeob.save()content = {"info": "上傳成功!", "image": filename,"status":200}else:content = {"info": "標題重復,請重新輸入","status":400}except:content = {"info": "上傳失敗!","status":400}return render(request, "info.html", content)render方法的作用:
????????結合一個給定的模板和一個給定的上下文字典,并返回一個渲染后的 HttpResponse 對象。
通俗的講就是把context的內容, 加載進templates中定義的文件, 并通過瀏覽器渲染呈現。
?5、查看相冊信息
5.1、編寫網頁部分
在templates文件夾中創建一個lookAlbum的網頁文件,編寫代碼:
<!DOCTYPE html> <html lang="en"> <head><meta charset="UTF-8"><title>瀏覽相冊信息</title><script>//自定義執行信息刪除提示判斷,參數uu是成功的刪除url地址function doDel(url){if(confirm("確定要刪除嗎?")){//網頁跳轉window.location=url;}}</script> </head> <body><center>{% include 'base.html' %}<h3>瀏覽相冊圖片信息</h3><form method="get" action="{% url 'look' 1 %}">標題:<input type="text" name="keyword"/><input type="submit" value="搜索"/></form><br/><table width="800" border="1"><tr><th>ID號</th><th>標題</th><th>圖片</th><th>時間</th><th>操作</th></tr>{% for album in AlbumList %}<tr><td>{{ album.id }}</td><td>{{ album.title }}</td><td style="text-align:center;"><a href="{% url 'lookBigImage' album.id %}"><img src='/static/small/s_{{ album.title }}.{{ album.type }}'/></a><!--點擊后放大比例查看圖片--></td><td>{{ album.add_time|date:'Y-m-d' }}</td><td><a href="{% url 'updata' album.id %}">編輯</a><a href="javascript:doDel('{% url 'del' album.id %}');">刪除</a></td></tr>{% endfor %}</table><br/><!--分頁功能--><!--像這種{% url 'look' pIndex|add:-1 %},后面跟著的是django的過濾器,可以自行去了解下,就不做細講--><a href="{% url 'look' pIndex|add:-1 %}{{mywhere}}">上一頁</a> {% for p in pageList %}{% if pIndex == p %} <a href="{% url 'look' p %}{{mywhere}}" style="color:red;">{{ p }}</a>{% else %} <a href="{% url 'look' p %}{{mywhere}}" >{{ p }}</a>{% endif %}{% endfor %} <a href="{% url 'look' pIndex|add:1 %}{{mywhere}}">下一頁</a><br/><br/><br/></center> </body> </html>對應分頁內容看不懂的,可以看接下來的后端代碼,結合起來看。
5.2、編寫后端代碼
在urls.py中添加:
path('look/<int:pIndex>',views.look,name="look"),在views.py中添加:
def look(request, pIndex=1):try:kw = request.GET.get('keyword', None)mywhere = ""if kw != None:ulist = Album.objects.filter(title__contains=kw)mywhere = "?keyword=" + kwelse:ulist = Album.objects.all()p = Paginator(ulist, 5) # 返回分頁對象,參數為列表數據,每面數據的條數# 設置頁號邊界if pIndex < 1:pIndex = 1if pIndex >= p.num_pages: # 頁面總數pIndex = p.num_pages# 下標以1開始,如果提供的頁碼不存在,拋出InvalidPage異常。這個方法比較方便快捷的分頁,輸入第幾頁,就會放回對應頁數的數據,在這里進行的篩選。list = p.page(pIndex) content = {"AlbumList": list, "pIndex": pIndex, "pageList": p.page_range, "mywhere": mywhere}return render(request, "lookAlbum.html", content)except:content = {"info": "沒有找到用戶信息","status":400}return render(request, "info.html", content)給講下分頁思路:
? ? ? ? 當點擊搜索后,會將輸入的內容(kw)發送到后端,設置mywhere = "?keyword=" + kw
,對數據庫所有標題進行模糊查找,放入一個列表中,用方法取出對應頁的數據然后放回到頁面中。簡答講下,要知道網址?后面的就是get類型的訪問參數,(http://127.0.0.1:8000/look/1?keyword=3),類似這種,具體看代碼吧。
6、修改相冊信息
6.1、編寫網頁部分
在templates文件夾中創建一個updata的網頁文件,編寫代碼:
<!DOCTYPE html> <html lang="en"> <head><meta charset="UTF-8"><title>修改相冊信息</title><script>// 和添加操作一樣,縮減大小立即顯示function setImagePreview(avalue) {var docObj = document.getElementById("doc");var imgObjPreview = document.getElementById("preview");if (docObj.files && docObj.files[0]) {//火狐下,直接設img屬性imgObjPreview.style.width = '500px';imgObjPreview.style.height = '330px';//imgObjPreview.src = docObj.files[0].getAsDataURL();//火狐7以上版本不能用上面的getAsDataURL()方式獲取,需要一下方式imgObjPreview.src = window.URL.createObjectURL(docObj.files[0]);}return true;}</script> </head> <body><center>{% include 'base.html' %}<h2>修改相冊信息</h2><form method="post" action="{% url 'doupdata' id %}" enctype="multipart/form-data">{% csrf_token %}<table width="400"><tr><td>標題:</td><td><input type="text" name="title" value="{{ title }}"></td></tr><tr><td>圖片:</td><td><input type="file" name="pic" id="doc" onchange="setImagePreview(this)"/><br></td></tr></table><input type="submit" value="編輯"> <input type="reset" value="重置"></form><br/><br/><img src='/static/{{ title }}.{{ type }}' width="500" height="330" id="preview"/></center> </body> </html>6.2、編寫后端部分
在urls.py中添加:
path('updata/<int:uid>',views.updata,name="updata"), # 在瀏覽頁點擊修改后的路由路徑 path('doupdata/<int:uid>',views.doupdata,name="doupdata"), # 執行修改命令的功能在views.py中添加:
# 將信息記錄并跳轉到修改頁面 def updata(request, uid):# 查詢mod = Album.objectsobjects = mod.filter(id=uid)[0]content = {"id": objects.id, "title": objects.title, "type": objects.type, "time": objects.add_time}return render(request, "updata.html", content)# 修改功能 def doupdata(request, uid):try:# 判斷標題是否重復mod = Album.objectsulist = mod.filter(title=request.POST['title']).exclude(id=uid)if len(ulist) == 0:fileImage = request.FILES.get("pic", None)if fileImage == None:content = {"info": "暫無上傳文件!","status":400}return render(request, "info.html", content)fileType = fileImage.name.split('.').pop()if fileType.lower() != "jpg" and fileType.lower() != "png" and fileType.lower() != "jpeg":content = {"info": "請選擇圖片文件!","status":400}return render(request, "info.html", content)ob = Album.objects.get(id=uid)oldTitle = ob.title + "." + ob.type# 刪除舊照片os.remove("./static/small/s_" + oldTitle)os.remove("./static/" + oldTitle)# 修改標題ob.title = request.POST['title']# 修改類型ob.type = fileTypefilename = request.POST['title'] + "." + fileType# 保存圖片到本地Imagefile = open("./static/" + filename, "wb+")for chuck in fileImage.chunks():Imagefile.write(chuck)Imagefile.close()# 執行圖片縮放并保存到本地im = Image.open("./static/" + filename)im.thumbnail((75, 75))im.save("./static/small/s_" + filename, None)ob.save()content = {"info": "修改成功!","status":200}else:content = {"info": "標題重復,請重新輸入","status":400}except:content = {"info": "修改失敗!","status":400}return render(request, "info.html", content)這里應該都知道吧,對應部分都有注釋。
7、刪除相冊信息
網頁部分與第5步結合,添加了刪除提示,以防誤點:
7.1、編寫后端部分
在urls.py中添加:
path('delete/<int:uid>',views.delete,name="del"),在views.py中添加:
def delete(request, uid):try:ob = Album.objects.get(id=uid)oldTitle = ob.title + "." + ob.type# 刪除舊照片os.remove("./static/small/s_" + oldTitle)os.remove("./static/" + oldTitle)# 刪除數據庫信息ob.delete()content = {"info": "刪除成功!","status":200}except:content = {"info": "刪除失敗!","status":400}return render(request, "info.html", content)8、附加:點擊圖片變大
?網頁代碼請看第5點,圖片標簽被a標簽包含了。
8.1、編寫后端部分
在urls.py中添加:
path('lookBigImage/<int:uid>',views.lookBigImage,name="lookBigImage"),在views.py中添加:
def lookBigImage(request, uid):try:ob = Album.objects.get(id=uid)image = ob.title + "." + ob.typecontent = {"imageLook": image}return render(request, "info.html", content)except:content = {"info": "查看失敗","status":400}return render(request, "info.html", content)好了,這個在線相冊管理系統就寫完啦,運行看看效果吧,如果哪里有看不懂的地方就在評論區中留言或私信我哦!
未經允許,請勿轉載!
總結
以上是生活随笔為你收集整理的Django--在线相册管理系统(2)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: topogun3自己编写的使用教程
- 下一篇: CSS相关知识点记录