views:

124

answers:

1

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?

+4  A: 

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
Will McCutchen
I confirm it works. I'll wait for a bit for a more elegant solution and if nothing shows up I'll mark your answer as accepted. Thanks for it, you've earned your 10 points.
Iker Jimenez
Unfortunately, this is currently the best way to do it.
Nick Johnson