I’m trying to relate all the objects created in a formset to an object created on the same webpage as the formset. So, an example of the code is this:
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)
The problem I’m having is that when trying to relate the formset object to the form one, it tells me that the form object doesn’t actually exist. It creates the object in the database however, just none of the formset objects. I get the error “Cannot assign “u””: “Species.BName” must be a “BModel” instance.” if that helps. Also, the relationship is a ForeignKey. Is there anyway to solve this? Thanks for your time.
This exact pattern is what inline model formsets are for.