gpt4 book ai didi

Django formset - 如何更新对象?

转载 作者:行者123 更新时间:2023-12-04 02:03:56 25 4
gpt4 key购买 nike

如何使用 request.POST 从表单集中更新对象?

这是我的代码,我的问题是这总是会创建一个新的 PhoneNumber目的。但是我想更新旧的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),
)

编辑:我创建了三个 PhoneNumberForms:
PhoneNumberFormSet = modelformset_factory(PhoneNumber, max_num=3, extra=3, exclude=('contact',))

编辑:使用 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),)

这种方法甚至为每个内联表单添加了一个删除复选框。简单而伟大。

最佳答案

而不是使用 modelformset_factory , 使用 inlineformset_factory - 见 the documentation here - 抱歉,最初应该向您指出这一点。

然后你可以删除 queryset 的东西,因为 inlineformset_factory 会处理这个,只需传递 instance参数(这里指的是父模型,即 Contact 对象)。您也不需要在保存时显式设置 contact 属性,因为这再次被处理。

关于Django formset - 如何更新对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1988968/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com