我是Django的新手。我很难完成此申请。总的来说,我正在尝试一种接受两个不同数字的表格,然后将这些数字加在一起。到目前为止,这就是我所拥有的,但是我知道某处一定有错误。另外,我不知道我需要确切返回什么。任何帮助将不胜感激。
此外,最好在新页面上显示输出。我想我可以通过添加另一个HTML文件来完成此操作。但是,请您提供如何完成此操作。
forms.py:
from django import forms
class InputForm(forms.Form):
x = forms.IntegerField(label='Enter first number: ')
y = forms.IntegerField(label='Enter second number: ')
views.py:
from django.shortcuts import render
from django.http import HttpResponse
from .forms import InputForm
def add(request):
form = InputForm(request.POST or None)
if request.method == 'POST':
form = InputForm(request.POST or None)
if form.is_valid():
cd = form.cleaned_data
input1 = cd['x']
input2 = cd['y']
output = input1 + input2
return ???
else:
form = InputForm()
return render(request, 'addition/home.html')
urls.py:
from django.urls import path
from . import views
urlpatterns = [
path('', views.add, name='addition-home'),
]
home.html:
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>Home</title>
</head>
<body>
<form class="addform" method="post">
{% csrf_token %}
<input type="number" name="firstnumber" label="Enter first number: ">
<input type="number" name="secondnumber" label="Enter second number: ">
<button type="submit" name="sumbit">Submit</button>
</form>
</body>
</html>
答案 0 :(得分:1)
也许可以在这里尝试
views.py
def add(request):
context = []
form = InputForm(request.POST or None)
if request.method == 'POST':
form = InputForm(request.POST or None)
if form.is_valid():
cd = form.cleaned_data
input1 = cd['x']
input2 = cd['y']
print(output)
# You should see the number in your terminal
context['output'] = output
# remove return
else:
form = InputForm()
return render(request, 'addition/home.html', context)
template.html
{{ output }}