首页 > 解决方案 > How to keep files in the formset after page reload? . Django

问题描述

Having spent few days trying to figure it out. Maybe it is a simply question for you, but, anyway…</p>

I have a view for the form within inline formset that receives and saves files + few text fields in a primary model form itself.

Problem is when form + formset are filled with text data for the main form and files for the formset, in case if main form is not valid, page gets reloaded and files from formset would get lost and I have to attach them again. I would like to have this situation fixed in a way that files after re rendering of the page would be present as well, but, unfortunatelli i can not find the solution.

My view is as following:

# only the portion that in charge for the above-mentioned logic
# files are getting lost in form2. With form 1 everything is OK

def viewname(request):
    if request.method == 'POST':
        form1 = MainForm(request.POST, request.FILES, prefix="form1")
        if form1.is_valid():
            prim = form1.save(commit=False)
            prim.author = request.user
            form2 = inline_formset(request.POST, request.FILES,
                                              prefix="form2", instance=prim)
        else:
            form2 = inline_formset(request.POST, request.FILES, prefix="form2")
            context = {"form1": form1, "form2": form2}
            return render(request, "create.html", context)

…
…
…

reload of the page is caused by clean() method in forms. It validates 2 fields mutual data, so that I cant move this validation to validators in form fields. Need to get cleaned data to compare 2 fields anyway.

标签: djangodjango-formsdjango-viewsdjango-validation

解决方案


可以通过应用程序“file_resubmit”来完成


推荐阅读