[英]Django can't process html form data
I have a simple Django site and I want to pass data from the first box, and return that value plus 5 to the second form box on the page. 我有一个简单的Django网站,我想从第一个框传递数据,然后将该值加5返回到页面上的第二个表单框。 I later plan on doing math with that first value but this will get me started. 我后来计划使用第一个值进行数学运算,但这将使我入门。 I am having a lot of trouble retrieving the form data. 我在检索表单数据时遇到很多麻烦。 I know I need to create a function in my views.py
file to process the form, and I need to put something in URLs.py
to retrieve the form data. 我知道我需要在views.py
文件中创建一个函数来处理表单,并且需要在URLs.py
放入一些URLs.py
以检索表单数据。 I have tried everything in tutorials, etc, but can't figure it out. 我已经尝试了教程等中的所有内容,但无法弄清楚。
My html template is a simple page that has a form with two fields and a submit button. 我的html模板是一个简单的页面,具有一个包含两个字段的表单和一个提交按钮。 Django runserver
pulls up the html page just fine. Django runserver
拉起html页面就好了。 Here is my code: 这是我的代码:
Views.py 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 urls.py
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.index, name='index'),
]
Here is my html template, index.html: 这是我的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>
You will need to populate the result to context variable which the template can access. 您将需要将结果填充到模板可以访问的上下文变量中。
view: 视图:
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)
then in your template: 然后在您的模板中:
<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>
Looks like you are quite new at Django, I recommend: 看来您是Django的新手,我建议:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.