Alex Rivera | Logout

Creating one Django Form to save two models

Asked 2013-04-08T22:00:21.777
16

I have the regular Django User model and a UserDetails model (OneToOneField with User), which serves as an extension to the User model. (I tried Django 1.5's feature and it was a headache with strangely horrible documentation, so I stuck with the OneToOneField option)

So, in my quest to build a custom registration page that will have a registration form comprised of the User fields and the UserDetails fields, I wondered if there was a way to generate the form automatically (with all of its validations) out of these two related models. I know this works for a form made of one model:

class Meta:
    model = MyModel

But is there anyway to get a similar functionality for a form comprised of two related models?

Edit
Report

1 Answer

17
from django.forms.models import model_to_dict, fields_for_model


class UserDetailsForm(ModelForm):
    def __init__(self, instance=None, *args, **kwargs):
        _fields = ('first_name', 'last_name', 'email',)
        _initial = model_to_dict(instance.user, _fields) if instance is not None else {}
        super(UserDetailsForm, self).__init__(initial=_initial, instance=instance, *args, **kwargs)
        self.fields.update(fields_for_model(User, _fields))

    class Meta:
        model = UserDetails
        exclude = ('user',)

    def save(self, *args, **kwargs):
        u = self.instance.user
        u.first_name = self.cleaned_data['first_name']
        u.last_name = self.cleaned_data['last_name']
        u.email = self.cleaned_data['email']
        u.save()
        profile = super(UserDetailsForm, self).save(*args,**kwargs)
        return profile
answered 2013-04-09T03:08:39.307

Your Answer