1
我有一個簡單的Django網站,我想從第一個框中傳遞數據,並將該值加5返回到頁面上的第二個表單框。我後來打算用第一個數值來做數學,但這會讓我開始。我在檢索表單數據時遇到了很多問題。我知道我需要在我的views.py
文件中創建一個函數來處理表單,並且我需要在URLs.py
中添加一些內容來檢索表單數據。我已經嘗試了所有的教程等,但無法弄清楚。Django無法處理HTML表單數據
我的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>
感謝您的響應。你是對的,我有一些基本的python經驗,但對Django來說是新的,並且正在爲之付出努力。在使用您的建議之後,我現在正在使用BrewSite.urls中定義的URLconf,Django嘗試使用這些URL模式,順序如下: ^ brew/ ^ admin/ 當前URL sendform /不匹配這些。」我需要添加一些東西到urls.py?我嘗試在我的模板中刪除action =「/ sendform」,但後來我得到了「失敗的原因:CSRF令牌丟失或不正確。」。如果我將操作更改爲/ brew /,也會得到同樣的結果。 –
我認爲這超出了你的問題,你需要在你的表單中放置'{%csrf_token%}',這會產生一個帶有標記的隱藏輸入字段。關於您的網址問題,您項目文件夾中的主要urls.py需要包含您的應用程序的urls.py,請在這裏查看我的視頻https://www.youtube.com/watch?v=c3C3hYbo37c –
將該行添加到我的模板形式做到了!非常感謝幫助,現在我終於可以繼續了。 –