Amanda_K96
Amanda_K96

Reputation: 55

Passing Variable (View --> Template --> View)

Problem: I want to generate a random number, and ask the user to calculate the addition of these two. Then, I want to evaluate the number and see if the solution is correct.

My issue: I can do everything except the evaluation bit, as the values of the random numbers change!

HTML file:

  <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 file:

class MyForm(forms.Form):
    num1 = forms.CharField(max_length=20)

VIEW file:

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

The error I get is "local variable 'a' referenced before assignment". I did try and change initialisation of a and b, and put the code right after the function declaration but that did not work either, as the function would compare the numbers (a + b) with another set of randomly generated numbers

Any help is much appreciated, or perhaps a new approach to this problem. Do note that I am a beginner in Python though

Upvotes: 0

Views: 37

Answers (1)

neverwalkaloner
neverwalkaloner

Reputation: 47364

You can try to store a and b in session data:

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

Upvotes: 1

Related Questions