with modelformset many formmodel form creating create django django-forms

modelformset - django formmodel



Django formset: ¿cómo actualizar un objeto? (1)

En lugar de usar modelformset_factory , use inlineformset_factory ; consulte la documentación aquí . Lo siento, debería haberle señalado inicialmente.

A continuación, puede soltar las cosas del conjunto de consultas, ya que inlineformset_factory se encarga de eso, y simplemente pasa el argumento de la instance (que aquí se refiere al modelo principal , es decir, el objeto de Contact ). Tampoco necesitará iterar explícitamente para establecer el atributo de contacto en el guardado, ya que una vez más eso se solucionó.

¿Cómo puedo actualizar un objeto de un formset usando request.POST ?

Aquí está mi código y mi problema es que esto siempre crea un nuevo objeto PhoneNumber . Pero quiero actualizar el antiguo objeto PhoneNumber .

def contact_detail(request, contact_id): contact = get_object_or_404(Contact, pk=contact_id) phone_number_list = PhoneNumber.objects.filter(contact=contact_id) if request.method == ''POST'': cform = ContactForm(request.POST, instance=contact) #the next line is probably wrong! phonenumberformset = PhoneNumberFormSet(request.POST, queryset=phone_number_list) if cform.is_valid() and phonenumberformset.is_valid(): phonenumber_instances = phonenumberformset.save(commit=False) for phonenumber in phonenumber_instances: phonenumber.contact = contact phonenumber.save() request.user.message_set.create(message=''The contact "%s" was chanced successfully.'' % contact.__str__()) return HttpResponseRedirect("/crm/contacts/?oby=1") else: cform = ContactForm(instance=contact) phonenumberformset = PhoneNumberFormSet(queryset=phone_number_list) return render_to_response( ''crm/contact_detail.html'', {''cform'': cform, ''phonenumberformset'': phonenumberformset,}, context_instance = RequestContext(request), )

Editar: creo tres PhoneNumberForms:

PhoneNumberFormSet = modelformset_factory(PhoneNumber, max_num=3, extra=3, exclude=(''contact'',))

Editar: la solución que usa inlineformset_factory:

@login_required def contact_detail(request, contact_id): contact = get_object_or_404(Contact, pk=contact_id) PhoneNumberInlineFormSet = inlineformset_factory(Contact, PhoneNumber, max_num=3) if request.method == ''POST'': cform = ContactForm(request.POST, instance=contact) classificationformset = ClassificationInlineFormSet(request.POST, request.FILES, instance=contact) addressformset = AddressInlineFormSet(request.POST, request.FILES, instance=contact) phonenumberformset = PhoneNumberInlineFormSet(request.POST, request.FILES, instance=contact) if cform.is_valid() and phonenumberformset.is_valid(): contact = cform.save() phonenumberformset.save() request.user.message_set.create(message=''The contact "%s" was chanced successfully.'' % contact.__str__()) return HttpResponseRedirect("/crm/contacts/?oby=1") else: cform = ContactForm(instance=contact) phonenumberformset = PhoneNumberInlineFormSet(instance=contact) return render_to_response( ''crm/contact_detail.html'', {''cform'': cform, ''phonenumberformset'': phonenumberformset,}, context_instance = RequestContext(request),)

Este enfoque incluso agrega una casilla de verificación Eliminar a cada formulario en línea. Fácil y genial