Reputation: 15
I would like to display data from a view after a calculation to a template. The View collects data from a Django form and then performs a simple calculation. However, the function does not redirect to the template.
views.py
from . import forms
from django.http import HttpResponseRedirect
from django.shortcuts import render,redirect
def index(request):
form = forms.InputForm()
return render(request, 'index.html', {'form': form})
def addition(a,b):
c = a + b
return c
def input_form_Addition(request):
if request.method == 'post':
form = forms.InputForm(request.POST)
if form.is_valid():
input1 = form.cleaned_data['input1']
input2 = form.cleaned_data['input2']
total = addition(input1,input2)
return render(request, 'output.html', {'total': total})
else:
form = forms.InputForm()
The template (output.html) looks like this:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Forms</title>
</head>
<body>
<p>The Sum is {{ total }}</p>
</body>
</html>
My url routing is as follows:
from django.urls import path
from .views import index
from simple_addition import views
urlpatterns = [
path('', views.index, name='index'),
path('output/', views.input_form_Addition, name='output')
]
My Django form displays well and looks as follows.
forms.py from django import forms
class InputForm(forms.Form):
input1 = forms.FloatField()
input2 = forms.FloatField()
And is displayed at:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Forms</title>
</head>
<body>
<h2>Addition Page</h2>
<p>Fill in two numbers to get their sum</p>
<form method="post">
{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Add" >
</form>
</body>
</html>
Upvotes: 1
Views: 4812
Reputation: 191
Can you put you form code ? (template and forms.py)
edit:
Ok i find your problem :
<form method="post">
{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Add" >
You miss a action for post form :
forms template :
<form method="post" action="/output/">
{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Add" >
</form>
urls.py
path('output/', views.input_form_Addition, name='output')
views.py
from . import forms
from django.http import HttpResponseRedirect
from django.shortcuts import render,redirect
def index(request):
form = forms.InputForm()
return render(request, 'index.html', {'form': form})
def addition(a,b):
c = a + b
return c
def input_form_Addition(request):
form = forms.InputForm(request.POST)
if form.is_valid():
input1 = form.cleaned_data['input1']
input2 = form.cleaned_data['input2']
total = addition(input1, input2)
return render(request, 'output.html', {'total': total})
Upvotes: 2
Reputation: 557
Just replace the line in functions input_form_Addition(request):
if request.method == 'post':
with
if request.method == 'POST':
Upvotes: 0