[Django]-Django formset is not valid- why not?

5👍

Your formset does not contain any data. You need to pass request.POST and request.FILES as the first and second argument (or as the data and files keyword arguments), but only if it is an actual form submission.

If there is no data passed into a form or formset, it is considered unbound, and will return False without checking for errors.

The usual pattern is to pass them when request.method == 'POST', and then validate the formset:

def upload_budget_pdfs(request, project_id):
    ...
    if request.method == 'POST':
        drawing_formset = DrawingUploadFormset(request.POST, request.FILES, prefix='drawings', queryset=...)
        if drawing_formset.is_valid():
            # save formset
            return HttpResponseRedirect(...)
    else:
        drawing_formset = DrawingUploadFormset(prefix='drawings', queryset=...)
    return render(...)  # Render formset

This will show a blank form on GET, a filled-in form with error messages on an unsuccessful submission, and it will save the formset and redirect on a successful submission.

👤knbk

Leave a comment