這是一個很棒的問題,因為delete是要把已存在資料庫內的物件刪除,若用input來輸入資料,容易打錯,改由dropdwon就可以直接取得資料庫的資料物件,供使用者選擇,這樣就可以避免打錯的問題。
其解決步驟如下:
1.首先由https://www.w3schools.com/tags/tryit.asp?filename=tryhtml_select,可以知道select標籤的語法,如下圖。
2.改寫HTML檔案,delete.html
3.在views.py的程式中新增第55行到第58行,因為原來的delete()函式並沒有讀取資料庫的內容。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 | from django.shortcuts import render, redirect from youtobeapp.models import video from youtobeapp.form import PostForm # Create your views here. def home(request): try: videos = video.objects.all() except: print("沒有任何資料") return render(request, 'index.html', locals()) def post(request): if request.method == "POST": name = request.POST["videoname"] width = int(request.POST["videowidth"]) height = int(request.POST["videoheight"]) src = request.POST["videosrc"] v = video.objects.create(name=name, width=width, height=height, src=src) v.save return redirect('/index/') return render(request, 'post.html', locals()) def postform(request): postform = PostForm() return render(request, "postform.html", locals()) def post2(request): if request.method == "POST": postform = PostForm(request.POST) if postform.is_valid(): name = postform.cleaned_data["name"] width = int(postform.cleaned_data["width"]) height = int(postform.cleaned_data["height"]) src = postform.cleaned_data["src"] v = video.objects.create(name=name, width=width, height=height, src=src) v.save return redirect('/index/') else: print("證驗有誤") else: postform = PostForm() return render(request, 'post2.html', locals()) def delete(request): if request.method == "POST": videoname=request.POST['videoname'] try: v = video.objects.get(name=videoname) v.delete() return redirect('/index/') except: print("讀取錯誤") try: videos = video.objects.all() except: print("沒有任何資料") return render(request, "delete.html", locals()) |
4.測試結果
上一篇文章:影片網站資料庫及後台管理(八) - 刪除資料
沒有留言:
張貼留言