Reputation: 2913
I am using the common pattren of using he Django User model while having a OneToOne relation via a Userprofile to extend the user.
I would like to have one view which allows me to set both User fields and UserProfile fields on the same form. It should apply both db transactions to User and Userprofile tables.
I would love to use the ModelForm however I dont find anyway that I can use two models in the same form.
How should I accomplish this ?
Upvotes: 1
Views: 238
Reputation: 39659
Create a model form for your user profile and add user related fields for user model e.g. first_name
and last_name
and save the user fields when profile model get saved:
class ProfileForm(forms.ModelForm):
first_name = forms.CharField('First Name', max_length=25)
last_name = forms.CharField('Last Name', max_length=25)
def __init__(self, *args, **kwargs):
super(ProfileForm, self).__init__(*args, **kwargs)
class Meta:
model = ProfileModel
exclude = ('user', )
def save(self, *args, **kwargs):
instance = super(ProfileForm, self).save(*args, **kwargs)
user = instance.user
user.first_name = self.cleaned_data['first_name']
user.last_name = self.cleaned_data['last_name']
user.save()
return instance
Upvotes: 2