'two button in a form to display a dictionary is not working

I want to use two buttons in a template form and run two action in a function. when I omit if with only a button, django runs , but when I add if in the codes to execute 2 action , it stops working in view: def result(request): num1 = int(request.GET["num1"]) num2 = int(request.GET["num2"])

if 'add' in request.POST:
    res = num1 + num2

if 'sub' in request.POST:
    res = num1 - num2

return render(request, 'home/result.html', {'result': res})

in template named clt

        <form action="result" >
            Enter 1st number : <input type="text" name="num1"><br>
            Enter 2st number : <input type="text" name="num2"><br>

            <button type="submit" name="subscribe">Subscribe</button>
            <button type="submit" name="unsubscribe">Unsubscribe</button>

        </form>

in template named result result : {{ result }}



Solution 1:[1]

In the code above your 'if' test does not match the name you have given the buttons. Try:

if 'subscribe' in request.POST:
    res = num1 + num2

if 'unsubscribe' in request.POST:
    res = num1 - num2

The formatting broke on your code, it looks like you are using GET to get the two variables. If that's working, no worries, but normally form posted data should be gotten by request.POST.get['num1']

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1