Django:在获取POST请求的同时维护服务器端数据?

2024-04-20 03:10:55 发布

您现在位置:Python中文网/ 问答频道 /正文

我是Django的新手,现在我已经完成了由7部分组成的教程,我正在努力学习更多,同时制作自己的应用程序。你知道吗

我的应用程序的一部分从用户那里获取输入,然后在生成输出之前需要一些非平凡的服务器端计算(例如,用户将经历一些等待)。因此,我不希望一次计算所有内容,而是希望有几个小表单,每个表单都将数据发送到服务器计算部分,然后等待它接收下一个表单。例如:

my_app: will have a form which asks the user for three numbers, it will subtract the first from 100, then add the second number to the result, and finally multiply the new result by the third input:

e.g.

my form

1st: 5

2ed: 7

3rd: 2

result: (((100 - 5) + 7) * 2) = 204

虽然上面的示例很简单,但我所做的工作需要一些时间(但是,如果不是第一个字段,则取决于上一个结果的结果)。你知道吗

我在这里学会了如何恰当地设置一个视图: Django: proper way to handle form with POST to the same page

那么,当用户输入表单的每个部分的数据时,如何进行这个串行计算呢?(并等待直到计算出上一个结果或直到用户发布下一个信息,然后继续)


Tags: theto数据django用户form应用程序表单
1条回答
网友
1楼 · 发布于 2024-04-20 03:10:55

我的第一个答案是“把答案藏在会议中”。比如说:

问题1.py

if form.is_valid():
    request.session['height'] = height_calc(form.cleaned_data['height'])

问题2.py:

if form.is_valid():
    request.session['weight'] = weight_calc(request.session['height'], 
                                            form.cleaned_data['weight'])

问题3.2:

if form.is_valid():
    # now we have everything so do the final calculation
    final_result = final_calc(request.session['height'],
                              request.session['weight'],
                              form.cleaned_data['favorite_color'])

相关问题 更多 >