Din
Din

Reputation: 71

Adding two numbers and show the output on the same page

I am new to Django, I am not sure if I could do action and show result on the same page. For this page I want to add two numbers that are entered on textarea a1 and a2 together, and output it on textarea a3.

Now, the error is showing Page not found (404), I guess it is something to do with my routing.

And if I am doing dynamic content like this, should I use VueJS or react instead?

Here is my view:

def add(request):
    """The Cipher and Decipher page"""
    res = 0
    val1 = int(request.GET.get('a1', 0))
    val2 = int(request.GET.get('a2', 0))
    res = val1 + val2

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

my html (add.html):

{% block content %}
<h1>Addition</h1>
    <form action="add">
        <textarea rows="10" cols="50" name='a1' ></textarea>
        <textarea rows="10" cols="50" name='a2' ></textarea>
        <button type="submit" name="add">Calculate</button>

        <textarea rows="10" cols="50" name="a3" >{{result}} </textarea>
    </form>
{% endblock content  %}

my url.py:

app_name = 'morse_logs'

urlpatterns = [
    # Home Page
    path('', views.index, name='index'),
    # Page that shows all topics
    path('topics/', views.topics, name='topics'),
    # Page that do addition
    path('add/', views.add, name='add'),


]

Upvotes: 0

Views: 136

Answers (1)

neverwalkaloner
neverwalkaloner

Reputation: 47364

You specify in form's action attribute url where form should be send. You have add here which is not valid url. Instead you can just put "" here to show that form shoul be send to the current url:

{% block content %}
<h1>Addition</h1>
    <form action="" method="get">
        <textarea rows="10" cols="50" name='a1' ></textarea>
        <textarea rows="10" cols="50" name='a2' ></textarea>
        <button type="submit" name="add">Calculate</button>

        <textarea rows="10" cols="50" name="a3" >{{result}} </textarea>
    </form>
{% endblock content  %}

Upvotes: 1

Related Questions