簡體   English   中英

Django無法處理html表單數據

[英]Django can't process html form data

我有一個簡單的Django網站,我想從第一個框傳遞數據,然后將該值加5返回到頁面上的第二個表單框。 我后來計划使用第一個值進行數學運算,但這將使我入門。 我在檢索表單數據時遇到很多麻煩。 我知道我需要在views.py文件中創建一個函數來處理表單,並且需要在URLs.py放入一些URLs.py以檢索表單數據。 我已經嘗試了教程等中的所有內容,但無法弄清楚。

我的html模板是一個簡單的頁面,具有一個包含兩個字段的表單和一個提交按鈕。 Django runserver拉起html頁面就好了。 這是我的代碼:

Views.py

from django.shortcuts import render
from django.http import HttpResponse
from django.template import loader
from django import forms

def index(request):
    return render(request, 'brew/index.html')

 #Here I want a function that will return my form field name="input", 
 #and return that value plus 5 to the form laveled name="output". 
 #I will later us my model to do math on this, but I cant get 
 #this first part working

urls.py

from django.conf.urls import url
from . import views

urlpatterns = [
    url(r'^$', views.index, name='index'),    
]

這是我的html模板index.html:

<html>
<head>
<title>Gravity Calculator</title>
</head>
<body>
<h1>Gravity Calculator</h1>
<p>Enter the gravity below:</p>
<form action="/sendform/" method = "post">
    Enter Input: <br>
    <input type="text" name="input"><br>
    <br>
    Your gravity is: <br>
    <input type="text" name="output" readonly><br>
    <br>
    <input type="submit" name="submit" >        
</form>
</body>
</html>

您將需要將結果填充到模板可以訪問的上下文變量中。

視圖:

def index(request):
    ctx = {}
    if request.method == 'POST' and 'input' in request.POST:
        ctx['result'] = int(request.POST.get('input', 0)) + 5
    return render(request, 'brew/index.html', ctx)

然后在您的模板中:

<html>
<head>
<title>Gravity Calculator</title>
</head>
<body>
<h1>Gravity Calculator</h1>
<p>Enter the gravity below:</p>
<form action="/sendform/" method = "post">
    Enter Input: <br>
    <input type="text" name="input"><br>
    <br>
    Your gravity is: <br>
    <input type="text" name="output" value="{{ result }}" readonly><br>
    <br>
    <input type="submit" name="submit" >        
</form>
</body>
</html>

看來您是Django的新手,我建議:

  • 使用基於方法的視圖,直到您滿意為止,然后
  • 開始使用基於類的視圖,其優勢是代碼可重用性,但最終基於類的視圖會吐出視圖方法,ccbv.co.uk是一個很好的參考站點
  • 使用表單類

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM