views:

162

answers:

2

Hi all,

I'm using a Modelform for User to edit first_name and last_name, but I want an extra field from UserProfile (which has a 1-to-1 relation with User) added to this.

class UserProfileInfoForm(forms.ModelForm):
    """ Profile Model field specifications for edit.
    """
    class Meta:
        model = User
        fields = ('first_name', 'last_name', 'user_phonemobile')

    first_name = forms.CharField(
                            label = _('First name'),
                            max_length = 30,
                            required = True
                            )
    last_name = forms.CharField(
                            label = _('Last name'),
                            max_length = 30,
                            required = True
                            )
    user_phonemobile = forms.CharField(
                            label = _('Mobile phone'),
                            max_length = 15,
                            required = False,
                            )

I have the extra field in the ModelForm (and displayed on the page) but I can't get it to populate with the value from the other model (UserProfile). Been trying to do it subclassing the init of the modelform but no luck so far.

I could ofcourse make it a normal form and populate it like this in my view

userdata  = request.user.get_profile()
data = {
    'first_name': request.user.first_name,
    'last_name': request.user.last_name,
    'user_phonemobile': userdata.user_phonemobile,
    }
profileinfoform = UserProfileInfoForm(data)

But when adding extra fields in the future it feels like this will clutter my view definition.

Regards,

Gerard.

+1  A: 

I believe you're looking for inline formsets. They are designed for working with related objects.

Ben James
Thanx Ben, I got it working, but in my case it feels like using a canon to kill a mosquito. It is handy though for editing multiple 1-to-many's.Since I only have a 1-to-1 relation is there another way to acquire a field from a model within my form definition?
GerardJP
+1  A: 

I usually just create two forms, one for each model. See e.g. this message for an example.

akaihola
Hi akaihola, as it seems this way would have been the easiest. I assume the user_form and profile_form in the example are ModelForms?
GerardJP
@GerardJP Yes. Just remember to first validate both, then save.
akaihola