表单集正确存储在数据库中,这是代码
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))
我需要编辑多个formset,这是我的代码 这段代码是创建新对象,而不是修改现有数据库
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)
以特定方式修改对象,但例如失败。
然后我可以更新formset,因为我已经保存在数据库中。欢迎任何帮助...... 我没有把所有代码都用来简化有问题的例子
答案 0 :(得分:0)
您可以像这样初始化您的formset:
RestauranteFormSet = modelformset_factory(Restaurante, extra=2)
restaurante_formset = RestauranteFormSet(queryset=Restaurante.objects.all())
和request.POST
formset_restaurante = RestauranteFormSet(request.POST, queryset=Restaurante.objects.all())