I want to create an Entity Group relationship in an Entity that is being created through a ModelForm.
How do I pass the parent instance and set the parent=
attribute in the ModelForm?
I'll be interested to see if you get any good solutions to this problem. My own solution, which is far from elegant, is to do this:
book = models.Book(title='Foo')
chapter = models.Chapter(parent=book, title='dummy')
form = forms.ChapterForm(request.POST, request.FILES, instance=chapter)
Basically, I first create a dummy object (chapter
in this case) with the correct parent relationship and then pass that as the instance
argument to the form's constructor. The form will overwrite the throwaway data I used to create the dummy object with the data given in the request. At the end, to get the real child object, I do something like this:
if form.is_valid():
chapter = form.save()
# Now chapter.parent() == book