2019年11月3日 星期日

[ Django ] 影片網站資料庫及後台管理(七) - 資料新增並驗證

本篇文章動手實作新增第四筆影片資料(如下圖),並使用驗證表單。


1.撰寫post2.html

2.新增路徑urls.py

 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
"""youtobeproj URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/2.2/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  path('', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  path('', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.urls import include, path
    2. Add a URL to urlpatterns:  path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path
from youtobeapp.views import home, post, postform, post2

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', home),
    path('index/', home),
    path('post/', post),
    path('postform/', postform),
    path('post2/', post2),
]

3.在views.py上新增post2函式

 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
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())

4.執行127.0.0.1:8000/post2,隨意輸入資料

5.輸入正確資料

6.執行結果

上一篇文章:影片網站資料庫及後台管理(六) - 表單模型化
下一篇文章:影片網站資料庫及後台管理(八) - 刪除資料

沒有留言:

張貼留言