views:

136

answers:

2

Is it possible to have multiple models included in a single ModelForm in django? I am trying to create a profile edit form. So I need to include some fields from the User model and the UserProfile model. Currently I am using 2 forms like this

class UserEditForm(ModelForm):

    class Meta:
        model = User
        fields = ("first_name", "last_name")

class UserProfileForm(ModelForm):

    class Meta:
        model = UserProfile
        fields = ("middle_name", "home_phone", "work_phone", "cell_phone")

Is there a way to consolidate these into one form or do I just need to create a form and handle the db loading and saving myself?

A: 

You probably should take a look at Inline formsets. Inline formsets are used when your models are related by a foreign key.

John Percival Hackworth
Inline formsets are used when you need to work with a one to many relationship. Such as a company where you add employees. I am trying combine 2 tables into one single form. It is a one to one relationship.
Jason Webb
The use of an Inline formset would work, but would likely by less than ideal. You could also create a Model that handles the relation for you, and then use a single form. Just having a single page with 2 forms as suggested in http://stackoverflow.com/questions/2770810/muliple-models-in-a-single-django-modelform/2774732#2774732 would work.
John Percival Hackworth
+1  A: 

You can just show both forms in the template inside of one <form> html element. Then just process the forms separately in the view. You'll still be able to use form.save() and not have to process db loading and saving yourself.

In this case you shouldn't need it, but if you're going to be using forms with the same field names, look into the prefix kwarg for django forms. (I answered a question about it here).

Zach
That is what I am currently doing. It seemed a little dirty for django so I was hoping there was a cleaner way. Thanks for the help.
Jason Webb