在 Django 中处理表单集

Handling formsets in Django

提问人:Ravdar 提问时间:11/15/2023 最后编辑:Ravdar 更新时间:11/15/2023 访问量:24

问:

在我的 django 项目中,我想使用表单集,但我在处理 POST 请求时遇到了问题。

我是这样定义我的表单集的:

strategy_settings = formset_factory(StrategySettings)
strategy_formset = strategy_settings(request.POST)

然后,如果表单有效,我尝试遍历表单集中的所有表单:

if strategy_formset.is_valid():
    for form in strategy_formset:
        data = form.cleaned_data["data"]

但问题是,尽管我用适当的数据填写了表单,但表单无效,我通过在控制台中打印语句来检查这一点。没有出现错误,当我提交表单时,表单集只是从页面中消失。

以下是我的完整观点:

def input_view(request):    
    if request.method =="POST":
        simulation_form = SimulationSettings(request.POST) # Regular form
        strategy_settings = formset_factory(StrategySettings) # Formset
        strategy_formset = strategy_settings(request.POST) # Formset
        if simulation_form.is_valid() and strategy_formset.is_valid():
            print("valid")
            initial_amount = simulation_form.cleaned_data['initial_amount']
            number_of_simulations = simulation_form.cleaned_data['number_of_simulations']
            number_of_trades = simulation_form.cleaned_data['number_of_trades']
            values_from_all_forms = []
            for form in strategy_formset:
                accuracy = form.cleaned_data['accuracy']/100
                take_profit = form.cleaned_data['take_profit'] / 100
                stop_loss = form.cleaned_data['stop_loss'] / 100
                max_dd_list = []
                for simulation in range(0, number_of_simulations):
                    trades = (["W"] * int(number_of_trades*accuracy)) + (["L"] * int(number_of_trades * (1-accuracy)))
                    random.shuffle(trades)
                    current_amount = initial_amount
                    current_amount_list = []
                    profit_list = []
                    for trade in trades:
                        if trade ==  "W":
                            current_amount = current_amount + current_amount*take_profit
                        else:
                            current_amount = current_amount - current_amount*stop_loss
                        profit = current_amount/initial_amount * 100 - 100
                        profit = str(round(profit,2))+"%"
                        profit_list.append(profit)
                        current_amount_list.append(round(current_amount,2))
                    max_dd = round((1 - min(current_amount_list)/initial_amount) * 100,2)
                    max_dd_list.append(max_dd)
                    money_at_the_end = round(current_amount,2)
                    simulation+=1
                trades_table = {"Win or Lose" : trades}
                df = pd.DataFrame(trades_table)
                df.index +=1
                trades_table_html = df.to_html(classes="table table-striped")
                data = {"Current amount":current_amount_list, "Profit":profit_list}
                df = pd.DataFrame(data)
                main_table_html = df.to_html(index=False,classes="table table-striped")
                min_max_dd = min(max_dd_list) * (-1)
                avg_max_dd = round(np.mean(max_dd_list),2)* (-1)
                max_max_dd = max(max_dd_list)* (-1)
                take_profit = str(take_profit * 100) + "%"
                stop_loss = str(stop_loss * 100) + "%"
                accuracy = str(accuracy * 100) + "%"
                all_values = {"take_profit":take_profit, "stop_loss":stop_loss, "accuracy":accuracy, "profit":profit,"main_table_html":main_table_html,"money_at_the_end":money_at_the_end,"min_max_dd":min_max_dd, "avg_max_dd":avg_max_dd, "max_max_dd":max_max_dd, "form": form}
                values_from_all_forms.append(all_values)
            return render(
                request,
                "strategy_simulator/results_view.html",
                {"values_form_all_forms":values_from_all_forms, "trades_table_html":trades_table_html },
            )
        else:
            print("not valid")
    else:
        print("get")
        simulation_form = SimulationSettings()
        strategy_settings = formset_factory(StrategySettings)
        strategy_formset = strategy_settings()
    return render(
        request,
        "strategy_simulator/input_view.html",
        {"simulation_form": simulation_form, "strategy_formset": strategy_formset},
    )

您知道什么是不正确的以及为什么我的帖子请求无效吗?提前感谢您的帮助。

编辑:

我已经在另一个视图中测试了这个表单集,它似乎工作正常,它是有效的:

def test_view(request):
    strategy_settings = formset_factory(StrategySettings) 
    if request.method == "POST":
        strategy_formset = strategy_settings(request.POST)
        if strategy_formset.is_valid():
            print("valid")
            for form in strategy_formset:
                print(form.cleaned_data)
            return render(request, "strategy_simulator/test_view_success.html", {"strategy_formset":strategy_formset})
            
        else:
            print("not valid")
            print(strategy_formset.error)
            return render(request, "strategy_simulator/test_view_failure.html", {"strategy_formset":strategy_formset})
    else:
        strategy_formset = strategy_settings()
    return render(request, "strategy_simulator/test_view.html", {"strategy_formset":strategy_formset})

现在我更加困惑了。我不明白为什么我首先显示的具有相同数据的表单集被认为是无效的。

django post django-forms formset

评论

0赞 CoffeeBasedLifeform 11/15/2023
在您的第一个视图中,您也在验证 - 也许这是无效的形式。simulation_form
0赞 Ravdar 11/16/2023
它是有效的,我检查过

答: 暂无答案