这是此处Coding mental block with specific Django task
的最后一个问题的延续答案是:
纯粹的django解决方案将是:
num1
,num2
和result
)num1
和num2
num1
和num2
字段应该只读)result
字段中输入答案并提交表单num1 + num2 == result
但是,当我正在完成这些步骤时,我的表单没有正确呈现。
views.py
def form_handle(request):
form = MyForm()
if request.method == 'POST':
form = MyForm(request.POST)
if form.is_valid():
cd = form.cleaned_data
a = cd.get('a')
return render(request, "rr.html", {})
forms.py
class MyForm(forms.Form):
a = forms.CharField(max_length=20)
mat = forms.CharField(max_length=200)
html文件
<form action="{% url 'form_handle' %}" method="POST">{% csrf_token %}
{{form.as_p}}
<button type="submit">Submit</button>
</form>
当我加载页面时,我看到的只是一个提交按钮。 As pictured
有人可以告诉我哪里出错了吗?
答案 0 :(得分:0)
如果我理解正确,您在html文件中调用的form
是views.py中函数form
中的post_question
,不是吗?课程QuestionForm
?在哪里?你能告诉我们它的代码吗?因为我看到,类MyForm
在文件views.py中仍未使用。如果您还在views.py和类QuestionForm
中向我们展示导入,而不仅仅是一个荒谬的MyForm
,那会更容易。欢呼!
答案 1 :(得分:0)
执行以下操作: 如果表格有效,则检查条件否则张贴空白表格; 如果表单有效但结果答案错误,则重定向到您希望重定向的上一个网址
def form_handle(request):
if request.method == 'POST':
form = MyForm(request.POST) # if post method then form will be validated
if form.is_valid():
cd = form.cleaned_data
num1 = cd.get('num1')
num2 = cd.get('num2')
result = cd.get('result')
if float(num1) + float(num2) == float(result):
# give HttpResponse only or render page you need to load on success
return HttpResponse("valid entiries")
else:
# if sum not equal... then redirect to custom url/page
return HttpResponseRedirect('/') # mention redirect url in argument
else:
form = MyForm() # blank form object just to pass context if not post method
return render(request, "rr.html", {'form': form})