Mac
Mac

Reputation: 375

Form refreshes on submit - Django

I have a similar problem to the one mentioned here, Very simple user input in django

I have taken code samples from the above solution but I am still having the same problem. When I click on the calculate submit button the form just clears without taking me to the results view.

I'm certain that it is a small problem but I have been stuck on it for a while and could do with some help. I will post the relevant code below:

views.py:

from django.shortcuts import render
from django.http import HttpResponse


def index(request):
    return render(request, 'form.html')


def result(request):
    if request.method == "POST":
        number1 = request.POST.get("firstnumber", None)
        number2 = request.POST.get("secondnumber", None)
        answer = number1 + number2
        message = "The result of number1 + number2 is " + answer
    else:
        message = "You submitted an empty form"
    return HttpResponse(message)

form.html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
</head>
<body>

    <form method="POST" action="/calculator/">
        {% csrf_token %}
        Enter number 1: <br>
        <input type="text" name="firstnumber">
        <br>
        Enter number 2: <br>
        <input type="text" name="secondnumber">
        <br>
        <input type="submit" value="Calculate">
    </form>

</body>
</html>

calculator\urls.py:

from django.conf.urls import url
from . import views

urlpatterns = [
    url(r'^$', views.index, name='index'),
    url(r'^$', views.result, name='result'),
]

exercise4\urls.py:

from django.conf.urls import include, url
from django.contrib import admin

urlpatterns = [
    url(r'^calculator/', include('calculator.urls')),
    url(r'^admin/', admin.site.urls),
]

Upvotes: 2

Views: 866

Answers (1)

Pynchia
Pynchia

Reputation: 11590

When the form is submitted, it takes you to

<form method="POST" action="/calculator/">

which is the index view, since in calculator\urls.py you have

url(r'^$', views.index, name='index'),

and all such view does is returning the same page with the form itself.

Make the form point to the appropriate view (i.e. result)

<form method="POST" action="/calculator/result/">

and in calculator\urls.py

url(r'^result/$', views.result, name='result'),

However, that is not how forms are handled in django (normally).

Usually forms are handled by the same view, which discriminates on whether it was called with an HTTP POST method or with an HTTP GET.

In the former case, the view processes the submitted data (performing data validation as its first step). In the latter it returns the page with the form (i.e. what your index view is doing now).

Please take the time to carefully go through the excellent official pages dedicated to working with forms on Django's website

Upvotes: 2

Related Questions