2014年11月5日 星期三

Django筆記(8)-網頁標頭和表單提交



網頁資訊~查看header



步驟一
修改 helloWorld/views.py (完整代碼如下)

from django.shortcuts import render_to_response
from django.http import HttpResponse

def helloWorld(request):
    values = request.META.items()
    values = sorted(values, key=lambda d: d[0])
    html = []
    for k, v in values:
        html.append('<tr><td>{0}</td><td>{1}</td></tr>'.format(k, v))

    return HttpResponse('<table>{0}</table>'.format('\n'.join(html)))

步驟二
開啟 server 後~
在網址列輸入 127.0.0.1:8000/helloWorld/ 觀看結果


數據提交 - GET


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

<html>
    <head>
        <title> test </title>
    </head>
    <body>
    <!-- action 填的是對應到 view.py 的函數! -->
        <form aciton="/helloWorld/" method="get">
            <label >您的名字</label>
            <input type="text" name="name">
            <input type="submit" value="提交名字">
        </form>
    </body>
</html>

步驟二
修改 helloWorld/views.py (完整代碼如下)

from django.shortcuts import render_to_response
from django.http import HttpResponse

def helloWorld(request):
    if 'name' in request.GET:
        return HttpResponse('OK' if request.GET['name'] else 'NO')
    else:
        return render_to_response('test.html',locals())

步驟三
開啟 server 後~
在網址列輸入 127.0.0.1:8000/helloWorld/ 觀看結果

※表單的來源為函數helloWorld,提交後所對應的也是函數helloWorld,當表單遇到這種來源與去向相同的時候,可以讓form的action屬性為空!


數據提交 - POST


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

<html>
    <head>
        <title> test </title>
    </head>
    <body>
        <form aciton="/helloWorld/" method="post">
            <label >您的名字</label>
            <input type="text" name="name">
            <input type="submit" value="提交名字">
        </form>
    </body>
</html>

步驟二
修改 helloWorld/views.py (完整代碼如下)

from django.shortcuts import render_to_response
from django.http import HttpResponse

def helloWorld(request):
    if  'name' in request.POST:
        return HttpResponse('OK' if  request.POST['name'] else 'NO')
    else:
        return render_to_response('test.html',locals())

步驟三
修改 mysite/mysite/settings.py (暫時註解掉csrf防禦機制)

MIDDLEWARE_CLASSES = (
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.locale.LocaleMiddleware',
'django.middleware.common.CommonMiddleware',
#註解掉這一行
#'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
)

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


                                                                    上一篇    回目錄    下一篇

沒有留言:

張貼留言