我是新來的Django,我需要添加兩個數字x和y。
x和y是來自用戶的輸入。
這裏是我的views.py
from django.http import HttpResponseRedirect
from django.http import HttpResponse
from django.shortcuts import render
from .forms import InputForm
def add(request):
if request.method == 'POST': # If the form has been submitted...
form = InputForm(request.POST) # A form bound to the POST data
if form.is_valid(): # All validation rules pass
cd = form.cleaned_data # Process the data in form.cleaned_data
input1 = cd['x']
input2 = cd['y']
output = input1 + input2
return HttpResponseRedirect(request,'/thanks/')# Redirect to new url
else:
form = InputForm() # An unbound form
return render(request, 'scraper/base.html', {'form': form })
def thanks(request,output):
return render(request, 'scraper/base.html', output)
這裏是我的forms.py
from django import forms
class InputForm(forms.Form):
x = forms.IntegerField(label='Value of x')
y = forms.IntegerField(label='Value of y')
這裏是我的urls.py
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.add, name='add'),
url(r'^/', views.thanks , name='thanks'),
]
這裏是output.html
<html>
<head>
<title>Thanks</title>
</head>
<body>
<h1>Thanks</h1>
<h1> Output = {{output}} </h1>
</body>
</html>
用戶輸入x和y值,然後點擊添加按鈕輸出應該顯示在一個新的頁面,如output.html那麼該怎麼做?
我知道在views.py中有一些錯誤,我正在學習Django。請指出並告訴我實施這種方法的正確方法
我掙扎了5個小時。
請問你的urls.py是什麼樣子?根據錯誤信息有錯誤 – fodma1
請分享您的urls.py – utkbansal
嘗試:'HttpResponse('Result:{}'.format(output))''而不是'HttpResponseRedirect(...)' – ahmed