2014年11月5日 星期三

Django筆記(9)-表單的驗證與模型化


步驟一
在 helloWorld 目錄下新增 forms.py (完整代碼如下)

from django import forms

class checkForm(forms.Form):
    name = forms.CharField(max_length=10, required=True)
    phone = forms.CharField(max_length=10, required=True)
    #email = forms.EmailField(max_length=10, required=True)


步驟二
創建 helloWorld/templates/dataBase.html (完整代碼如下)

<html>
    <head>
        <title> dataBase </title>
        <meta charset='utf-8'>
    </head>
    <body style="font-family:Courier New;">
        <p>水果商有{{ vendors|length }}位</p>
        {% for v in vendors %}
            <p>水果商{{ forloop.counter }} : {{ v.name }}
&nbsp&nbsp&nbsp電話 : {{ v.phone }}</p>
        {% endfor %}
        <br>
    </body>
</html>

步驟三
修改 helloWorld/templates/test.html (完整代碼如下)

<html>
    <head>
        <title> test </title>
    </head>
    <body style="font-family:Courier New;">
        <form aciton="/helloWorld/" method="post">
            <label>名字 : {{ f.name }} </label><br>
            <label>電話 : {{ f.phone }}</label><br>
            <input type="hidden" name="ok">
            <input type="submit" value="提交">
        </form>
    </body>
</html>

步驟四
修改 mysite/helloWorld/view.py (完整代碼如下)

from django.shortcuts import render_to_response
from django.http import HttpResponse
from helloWorld.models import Vendor
from helloWorld.forms import checkForm

def helloWorld(request):
    if  'ok' in request.POST:
        name = request.POST['name']
        phone = request.POST['phone']

        #創建一個 forms.py 裡面的表單
        f = checkForm(request.POST)

        #以 forms.py 的條件來調用 is_valid() 驗證表單
        if  f.is_valid() and name != '請輸入名字':
            Vendor.objects.create(name=name, phone=phone)
            vendors = Vendor.objects.all()
            return render_to_response('dataBase.html',locals())
        else:
            return render_to_response('test.html',locals())
    else:
        f = checkForm(initial={'name':'請輸入名字'}) #表單欄位可以有預設值
        return render_to_response('test.html',locals())



步驟五
開啟 server 後~
在網址列打上 127.0.0.1:8000/helloWorld/ 觀看結果


                                                                    上一篇    回目錄   下一篇

沒有留言:

張貼留言