[Fixed]-Multiple Django Crispy Forms In One View

1👍

Firstly, you need to fix this line of your form’s clean method

def clean(self):
    ...
    Entry.objects.get(row_control=cleaned_data['row_control'],

You can’t assume that row_control will be in the cleaned_data. You either need to add a check if 'row_control' in cleaned_data or catch the KeyError, then update the rest of the method appropriately. You should fix this, even though you didn’t see this error until you put multiple forms on one page. It shouldn’t be possible to cause a 500 server error by leaving a value out of a POST request. Users could do this even if there is only one form on the page.

Validation is running for both forms, because you are instantiating both forms with the post data, regardless of which submit button was pressed.

row_control_form = RowControlForm(request.POST or None)
entry_form = EntryForm(request.POST or None)

You should only use the POST data for the form you wish to submit.

row_control_form = RowControlForm()
entry_form = EntryForm()

if 'row_control_submit' in request.POST:
    row_control_form = RowControlForm(request.POST)
    if row_control_form.is_valid():

if 'entry_submit' in request.POST:
    entry_form = EntryForm(request.POST)
    if entry_form.is_valid():
        entry_form.save()

Finally, it’s good practice to redirect the user once they have successfully submitted a valid form.

Leave a comment