[Fixed]-Creating one Django Form to save two models


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']
        profile = super(UserDetailsForm, self).save(*args,**kwargs)
        return profile


One way you can accomplish this, if you want to keep the ModelForm for User and UserDetails separate would be to return both forms to the front-end, and make sure they are both in the same html form element (i.e. all fields will be returned when data is posted).

This works if User and UserDetails don’t have any fields with the same name. To input the data in each ModelForm instance, you use the usual method:

    form_user = UserForm(request.POST, instance=request.user)
    form_user_details = UserDetailsForm(request.POST, instance=request.user.userdetails)

Leave a comment