问题:我想生成一个随机数,让用户计算这两个的相加。然后,我想评估这个数字,看看解决方案是否正确。
我的问题:除了评估位之外,我可以做任何事情,因为随机数的值会改变!
HTML文件:
<p> What is {{ a }} + {{ b }} ? </p>
<form action="{% url 'form_handle' %}" method="POST">{% csrf_token %}
{{form.as_p}}
<button type="submit">Submit</button>
</form>
表格文件:
class MyForm(forms.Form):
num1 = forms.CharField(max_length=20)
查看文件:
def form_handle(request):
if request.method == 'POST':
form = MyForm(request.POST) # if post method then form will be validated
if form.is_valid():
cd = form.cleaned_data
num1 = cd.get('num1')
#num2 = cd.get('num2')
#result = cd.get('result')
if float(num1) == float(a + b):
# give HttpResponse only or render page you need to load on success
return HttpResponse("Good job!")
else:
# if sum not equal... then redirect to custom url/page
return HttpResponseRedirect('rr/') # mention redirect url in argument
else:
a = random.randrange(5,10);
b = random.randrange(10,20);
form = MyForm() # blank form object just to pass context if not post method
return render(request, "rr.html", {'form': form, 'a': a, 'b':b})
我得到的错误是“在赋值之前引用了局部变量‘a’”。我确实尝试更改 a 和 b 的初始化,并将代码放在函数声明之后,但这也不起作用,因为该函数会将数字 (a + b) 与另一组随机生成的数字进行比较
非常感谢任何帮助,或者可能是解决此问题的新方法。请注意,尽管我是 Python 的初学者
您可以尝试在会话数据中存储a
和:b
def form_handle(request):
if request.method == 'POST':
form = MyForm(request.POST) # if post method then form will be validated
if form.is_valid():
cd = form.cleaned_data
num1 = cd.get('num1')
#num2 = cd.get('num2')
#result = cd.get('result')
a = request.session.get('a', 0)
b = request.session.get('b', 0)
if float(num1) == float(a + b):
# give HttpResponse only or render page you need to load on success
return HttpResponse("Good job!")
else:
# if sum not equal... then redirect to custom url/page
return HttpResponseRedirect('rr/') # mention redirect url in argument
else:
a = random.randrange(5,10);
b = random.randrange(10,20);
request.session['a'] = a
request.session['b'] = b
form = MyForm() # blank form object just to pass context if not post method
return render(request, "rr.html", {'form': form, 'a': a, 'b':b})
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句