我想更新可以包含不同条目的formset。我将能够提供预填充正确数据的formset,但是我做错了,因为它没有更新但是创建了一个新实例..
我看到 inlineformset_factory 但是因为我将多个值传递给formset,所以我无法使用它..
如果有人有任何指针,我会非常感激!
views.py
epis = Contact.objects.filter(episode=int(value))
ContactSet = formset_factory(Contact1Form, extra=len(epis), max_num=len(epis))
if request.method =='POST':
formset = ContactSet(request.POST)
if formset.is_valid():
for form in formset.forms:
age = form.cleaned_data['age']
bcg = form.cleaned_data['bcg_scar']
radio = form.cleaned_data['radiology']
profile = form.save(commit=False)
for i in epis:
profile.contact = i
fields = {'age': age, 'bcg_scar': bcg, 'radiology': radio}
for key, value in fields.items():
if value == u'':
setattr(profile, key, None)
else:
setattr(profile, key, value)
profile.save()
return render_to_response('success.html', {'location': location})
else:
dic = []
for c in epis:
aux = {}
for f in c._meta.fields:
if f.name not in ['contact_id', 'episode']:
aux[f.name] = getattr(c, f.name)
dic.append(aux)
formset = ContactSet(initial=dic)
return render_to_response('form.html',
{ 'msg': msg,
'location': location,
'formset': formset,
'word': word })
forms.py
class ContactForm(forms.ModelForm):
affinity = forms.ModelChoiceField(queryset=Affinity.objects.all(),
label=ugettext("Affinity"))
age = forms.IntegerField(label=ugettext("Age when diagnosed"),
required=False)
MAYBECHOICES = (
('', '---------'),
(ugettext('Yes'), ugettext('Yes')),
(ugettext('No'), ugettext('No')))
bcg_scar = forms.ChoiceField(choices=MAYBECHOICES, label=ugettext(
"BCG scar"), required=False)
radiology = forms.ModelChoiceField(queryset=Radiology.objects.all(),
label=ugettext("Radiology"),required=False)
class Meta:
model = Contact
任何指针都会有很大的帮助!
修改
来自凯瑟琳的一些建议
formset = ContactSet(request.POST, queryset=epis)
给了我这个错误:
__init__() got an unexpected keyword argument 'queryset'
我尝试更改
from django.forms.models import modelformset_factory
ContactSet = modelformset_factory(Contact1Form, extra=len(epis), max_num=len(epis))
出现了这个错误:
'ModelFormOptions' object has no attribute 'many_to_many'
然后看到要解决这个错误,我需要使用模型的名称。
ContactSet = modelformset_factory(Contact, extra=len(epis), max_num=len(epis))
我得到一个MultiValueDictKeyError
答案 0 :(得分:0)
您忘了在formset中添加instance
if request.method =='POST':
formset = ContactSet(request.POST, queryset=epis)
if formset.is_valid():
答案 1 :(得分:0)
MyFormSet = modelformset_factory(ModelName, form=MyForm)
qs = ModelName.objects.filter(user=request.user)
formset = MyFormSet(queryset=qs)