我想在计算模板后从视图显示数据。视图从Django表单收集数据,然后执行简单的计算。但是,该功能不会重定向到模板。
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()
模板(output.html)如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Forms</title>
</head>
<body>
<p>The Sum is {{ total }}</p>
</body>
</html>
我的网址路由如下:
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')
]
我的Django表单显示良好,外观如下。
forms.py 从Django导入表格中
class InputForm(forms.Form):
input1 = forms.FloatField()
input2 = forms.FloatField()
并显示在:
<!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>
答案 0 :(得分:2)
您可以输入表格代码吗? (模板和forms.py)
编辑:
好的,我找到了你的问题:
<form method="post">
{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Add" >
您错过了张贴表格的操作:
表单模板:
<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})
答案 1 :(得分:0)
只需替换函数 input_form_Addition(request):
中的行if request.method == 'post':
使用
if request.method == 'POST':