Handling formsets in Django

43 views Asked by At

In my django project, I want to use formsets, but I have a problem with handling the POST requests.

I defined my formset this way:

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

Then I tried to loop through all of the forms in a formset if the forms are valid:

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

But the thing is, although I fill the forms with proper data, the forms are not valid, I checked this by printing statements in the console. No error appears, when I submit the forms, formset just disappears from a page.

Here is my full view:

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},
    )

Do you have any idea what is incorrect and why my post requests are not valid? Thanks for help in advance.

EDIT:

I've tested this formset in another view and it seems to work fine, it is valid:

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})

Now I am even more confused. I don't get why the formset I showed first, with the same data, is considered invalid."

0

There are 0 answers