我正在尝试将在表单集中创建的所有对象与在与表单集相同的网页上创建的对象相关联。因此,代码示例如下:
def create_b(request):
SpeciesFormSet = modelformset_factory(Species, fields=('common', 'scientific'))
if request.method == 'POST':
formset = SpeciesFormSet(request.POST)
form1 = BForm(request.POST)
if form1.is_valid():
objcreate = BModel.objects.create(
name = form1.cleaned_data['name'],
...
)
objcreate.save()
for forms in formset.forms:
if forms.is_valid():
formset1 = Species.objects.create (
common = forms.cleaned_data['common'],
scientific = forms.cleaned_data['scientific'],
BName = form1.cleaned_data['name']
)
formset1.save()
else:
formset = SpeciesFormSet()
form1 = BForm()
c = {'SpeciesFormSet' : SpeciesFormSet, 'form1' : form1}
c.update(csrf(request))
return render_to_response('Forms/create_b.html', c)
return HttpResponseRedirect('/accounts/profile')
else:
formset = SpeciesFormSet()
form1 = BForm()
c = {'SpeciesFormSet' : SpeciesFormSet, 'form1' : form1}
c.update(csrf(request))
return render_to_response('Forms/create_b.html', c)
我遇到的问题是,当尝试将表单集对象与表单一相关联时,它告诉我表单对象实际上并不存在。但是,它在数据库中创建对象,但没有任何 formset 对象。我收到错误“无法分配“u''”:“Species.BName”必须是“BModel”实例。” 如果这有帮助。此外,该关系是一个外键。有没有办法解决这个问题?谢谢你的时间。