传递变量(视图 - >模板 - >视图)

时间:2018-01-02 04:49:02

标签: python django model-view-controller

问题:我想生成一个随机数,并要求用户计算这两者的加法。然后,我想评估数字,看看解决方案是否正确。

我的问题:除了评估位,我可以做任何事情,因为随机数的值会改变!

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>

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})

我得到的错误是&#34;本地变量&#39; a&#39;在转让之前引用&#34;。 我做了尝试更改a和b的初始化,并在函数声明之后放置代码,但这也不起作用,因为函数会将数字(a + b)与另一组数字进行比较随机生成的数字

非常感谢任何帮助,或者可能是解决此问题的新方法。请注意我是Python的初学者

1 个答案:

答案 0 :(得分:1)

您可以尝试将ab存储在session数据中:

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})