0

表单集正确存储在数据库中,这是代码

def crear_encuesta(request):
    HotelFormSet = formset_factory(HotelForm, extra=6)
    RestauranteFormSet = formset_factory(RestauranteForm, extra=6)
    if request.method == 'POST':              
        formset_restaurante = RestauranteFormSet(request.POST)
        formset_hotel = HotelFormSet(request.POST)
        if formset_restaurante.is_valid() and formset_hotel.is_valid():                

            for form in formset_restaurante.forms:
                restaurante = form.save(commit=False)
                restaurante.save()    

            for form in formset_hotel.forms:
                hotel = form.save(commit=False)          
                hotel.save()        

            messages.add_message(request, messages.SUCCESS, 'Encuesta salvada correctamente.')
            return HttpResponseRedirect('/crear_encuesta/') # Redirect after POST
    else:               
        formset_hotel = HotelFormSet()
        formset_restaurante = RestauranteFormSet()
    return render_to_response('encuestas/crear_encuesta.html',{               
        'formset_hotel':formset_hotel,
        'formset_restaurante':formset_restaurante
    },RequestContext(request))

我需要编辑几个表单集,这是我的代码, 这段代码是创建新对象,而不是修改现有数据库

def modificar_encuesta(request):
    HotelFormSet = formset_factory(HotelForm, extra=0)
    RestauranteFormSet = formset_factory(RestauranteForm, extra=0)
    if request.method == 'POST':
      formset_restaurante = RestauranteFormSet(request.POST)
      formset_hotel = HotelFormSet(request.POST)
      if formset_restaurante.is_valid() and formset_hotel.is_valid():        

        for form in formset_restaurante.forms:
            restaurante = form.save(commit=False)
            restaurante.save()


        for form in formset_hotel.forms:
            hotel = form.save(commit=False)
            hotel.save()

        messages.add_message(request, messages.SUCCESS, 'Encuesta modificada correctamente.')
    return HttpResponseRedirect('/modificar_encuesta/')

return render_to_response('encuestas/modificar_encuesta.html',{'flag':flag},RequestContext(request))

我的问题是我需要花一些时间来

formset_restaurante = RestauranteFormSet(request.POST)
formset_hotel = HotelFormSet(request.POST)

修改特定的对象,但例如失败。

然后我可以更新我已经保存在数据库中的表单集。欢迎任何帮助......我没有把所有代码都放在简化有问题的例子中

4

1 回答 1

0

您可以像这样初始化表单集:

RestauranteFormSet = modelformset_factory(Restaurante, extra=2)
restaurante_formset = RestauranteFormSet(queryset=Restaurante.objects.all())

request.POST

formset_restaurante = RestauranteFormSet(request.POST, queryset=Restaurante.objects.all())
于 2013-05-25T19:16:39.153 回答