编辑:
我是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个小时。
答案 0 :(得分:2)
您可以使用会话存储输出,然后在下一个视图中检索它。会话框架允许您基于每个站点访问者存储和检索任意数据。
编辑views.py,如下所示 -
def add(request):
if request.method == 'POST':
form = InputForm(request.POST)
if form.is_valid():
cd = form.cleaned_data
input1 = cd['x']
input2 = cd['y']
output = input1 + input2
# Save the result in the session
request.session['output'] = output
return HttpResponseRedirect('/thanks/')
else:
form = InputForm()
return render(request, 'scraper/base.html', {'form': form })
def thanks(request):
# Get the result from the session
output = request.session.pop('output', None)
return render(request, 'scraper/output.html', {'output':output})
你urls.py应该是 -
urlpatterns = [
url(r'^$', views.add, name='add'),
url(r'^thanks/$', views.thanks , name='thanks'),
]
答案 1 :(得分:1)
我认为您错误地使用了重定向,您无法在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('/thanks/{output}/'.format(output=output)) # Redirect to new url
else:
form = InputForm() # An unbound form
return render(request, 'scraper/base.html', {'form': form })
中发送参数,请在此处查看修改并查看documentation以获取更多解释:
<强> views.py 强>
url(r'^thanks/(?P<output>\d+)/$', thanks),
<强> urls.py 强>
{{1}}