我正在尝试找到一种稍后使用用户提供的变量的好方法。我已将其简化为这个最小的示例:
模型.py
class Input(models.Model):
x = models.IntegerField()
class InputForm(ModelForm):
class Meta:
model = Input
视图.py
def input(request):
if request.method == 'POST':
form = InputForm(request.POST)
if form.is_valid():
form.save()
return HttpResponseRedirect('/results')
else:
form = InputForm()
return render_to_response('input.html',
{'form':form}, context_instance=RequestContext(request))
def result(request):
# Here I would like to get the input from the form, e.g.
#
# x = request.GET["x"]
#
# or
#
# inp = InputForm(request.GET)
# x = inp.x
#
# Something like this, so that I can be able to write the line below:
return HttpResponse("x = %f" % x)
推荐的方法是什么?
编辑:
主要问题似乎是results函数中的request.GET dict是空的,即
def results(request):
return HttpResponse(request.GET)
只显示一个空白页面。然后当然 request.GET['x'] 给出了异常“Key 'x' not found in QueryDict: {}”。我的 input.html 看起来像这样:
<form method="post" action="">{% csrf_token %}
{{ form }}
<input type="submit" value="Compute" />
</form>
理想情况下,我希望能够将 request.GET 发送回 InputForm,就像在 FallenAngel 的原始答案中一样,但它不起作用,因为 request.GET 是空的。