Django-如何保存表单集模型

ia2d9nvy  于 2023-01-14  发布在  Go
关注(0)|答案(1)|浏览(147)

我有下面的视图代码

def edit_pal(request,pal_id):
    pals=palabout.objects.get(id=pal_id)
    form2=editpalForm(request.POST or None,instance=pals)
    RecipeIngredientFormset = modelformset_factory(palabout, form=editspalForm,extra=0)
    formset = RecipeIngredientFormset(request.POST or None,prefix=pals)
    context={
        "formset": formset,
        "form2":form2,
        "pals":pals
    }
    if request.method == 'POST':
        if form2.is_valid() and formset.is_valid():
            parent = form2.save(commit=False)
            parent.save()
            for form in formset:
                child = form.save(commit=False)
                child.recipe = parent
                child.save()
            context['message']='Data Saved'
        return redirect('hod:manage_pal')
    return render(request,"edit-pal.html",context)

我删除了formset.is_valid,所以它的工作,但它不工作时,我添加了更多的使用formset.is_valid,所以为什么不保存文件或详细信息显示?有人能帮助这个吗?

fae0ux8s

fae0ux8s1#

我认为你只需要重定向,如果表单是有效的,所以试试这个视图:

from django.shortcuts import get_object_or_404

def edit_pal(request,pal_id):
 
    pals=get_object_or_404(palabout,id=pal_id)
    if request.method == 'POST':
       
        form2=editpalForm(request.POST,instance=pals)
        RecipeIngredientFormset = modelformset_factory(palabout, form=editspalForm,extra=0)
        formset = RecipeIngredientFormset(request.POST,prefix=pals)

        if form2.is_valid() and formset.is_valid():
            parent = form2.save(commit=False)
            parent.save()
            for form in formset:
                child = form.save(commit=False)
                child.recipe = parent
                child.save()
            context['message']='Data Saved'
            return redirect('hod:manage_pal')
        else: # if the form is not valid
            return redirect("hod:some_error_page")
         
    else: # GET request
       
        RecipeIngredientFormset = modelformset_factory(palabout, form=editspalForm,extra=0)
        formset = RecipeIngredientFormset(prefix=pals)
        context={
            "formset": formset, 
            "form2":editpalForm(instance=pals),
            "pals":pals
        }
  
    return render(request,"edit-pal.html",context)

相关问题