2019年11月3日 星期日

[ Django ] 影片網站資料庫及後台管理(六) - 表單模型化

輸入資料需要驗證,若未驗證容易引起不可遇期的問題發生。本篇文章在於使用Python程式,設計驗證表單。

1.增加驗證表單程式form.py

1
2
3
4
5
6
from django import forms
class PostForm(forms.Form):
    name = forms.CharField(max_length=50, initial='')
    width = forms.IntegerField(max_value=1280, min_value=640)
    height = forms.IntegerField(max_value=1280, min_value=640)
    src = forms.CharField(max_length=50, initial='')

2.在views.py上增加postform函式。

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

3.增加路徑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
"""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

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

4.製作一個驗證表單form.html
5.記得使用python manage.py runserver啟動,並使用127.0.0.1:8000/postform來查看結果

6.在上圖的執行畫面中,按下右鍵選擇查看原始碼,就能瞭解本篇文章中,要表達如何用Python來設計HTML表單上的驗證功能。

上一篇文章:影片網站資料庫及後台管理(五) - 新增一筆資料
下一篇文章:影片網站資料庫及後台管理(七) - 資料新增並驗證

沒有留言:

張貼留言