我是新来的Django,我需要添加两个数字x和y。
x和y是来自用户的输入。
这里是我的views.py
from django.http import HttpResponseRedirect
from django.http import HttpResponse
from django.shortcuts import render
from .forms import InputForm
def add(request):
if request.method == 'POST': # If the form has been submitted...
form = InputForm(request.POST) # A form bound to the POST data
if form.is_valid(): # All validation rules pass
cd = form.cleaned_data # Process the data in form.cleaned_data
input1 = cd['x']
input2 = cd['y']
output = input1 + input2
return HttpResponseRedirect(request,'/thanks/')# Redirect to new url
else:
form = InputForm() # An unbound form
return render(request, 'scraper/base.html', {'form': form })
def thanks(request,output):
return render(request, 'scraper/base.html', output)
这里是我的forms.py
from django import forms
class InputForm(forms.Form):
x = forms.IntegerField(label='Value of x')
y = forms.IntegerField(label='Value of y')
这里是我的urls.py
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.add, name='add'),
url(r'^/', views.thanks , name='thanks'),
]
这里是output.html
<html>
<head>
<title>Thanks</title>
</head>
<body>
<h1>Thanks</h1>
<h1> Output = {{output}} </h1>
</body>
</html>
用户输入x和y值,然后点击添加按钮输出应该显示在一个新的页面,如output.html那么该怎么做?
我知道在views.py中有一些错误,我正在学习Django。请指出并告诉我实施这种方法的正确方法
我挣扎了5个小时。
请问你的urls.py是什么样子?根据错误信息有错误 – fodma1
请分享您的urls.py – utkbansal
尝试:'HttpResponse('Result:{}'.format(output))''而不是'HttpResponseRedirect(...)' – ahmed