robos85
robos85

Reputation: 2554

Edit profile with ModelForm and UserProfile

I use extended UserProfile. Now I want to make a profile edition. I need to place all my custom profile fields and email, firstname, lastname from original User model. I try to do this, but can't make it work. Email field is not shown. None of the User model are shown.

My forms:

class MainUserProfile(ModelForm):
    class Meta:
        model = User
        fields = ('email',)
class UserProf(MainUserProfile):    
    class Meta:
        model = UserProfile

My view:

form = UserProf(instance=request.user.get_profile())

UPDATE:

I made it:) Here's the code:

class EditCustomerForm(ModelForm):
    def __init__(self, *args, **kwargs):
        super(EditCustomerForm, self).__init__(*args, **kwargs)
        try:
            self.fields['email'].initial = self.instance.user.email
            self.fields['first_name'].initial = self.instance.user.first_name
            self.fields['last_name'].initial = self.instance.user.last_name
        except User.DoesNotExist:
            pass

    required_css_class = 'required'
    error_css_class = 'error'

    email = forms.EmailField(label=_(u"Email"))
    first_name  = forms.CharField(max_length=30, required=True, label=_(u'Forname'))
    last_name  = forms.CharField(max_length=30, required=True, label=_(u'Surname'))
    address = forms.CharField(max_length=255, min_length=10, required=True, label=_(u'Address'))

    class Meta:
        model = UserProfile
        fields = ('email', 'first_name', 'last_name', 'address')

    def clean_email(self):
        return check_email(self.cleaned_data['email'], self.instance.user.id)

    def save(self, *args, **kwargs):
        u = self.instance.user
        u.email = self.cleaned_data['email']
        u.save()
        profile = super(EditCustomerForm, self).save(*args,**kwargs)
        return profile

a form in a view:

if request.method == 'POST':
    form = EditCustomerForm(request.POST, instance=user)
else:
    form = EditCustomerForm(instance=user)

Upvotes: 11

Views: 4271

Answers (3)

JamesO
JamesO

Reputation: 25966

I don't think you can use ModelForm inheritance - http://code.djangoproject.com/ticket/7018 - contains a similar example.

You could either use formsets to combine both forms or if this is via the admin use inlines.

Upvotes: 0

Mahmoud Afarideh
Mahmoud Afarideh

Reputation: 376

You can pass initial data to form like this:

form = EditCustomerForm(instance=user, initial={
    'email' : user.email
    'first_name' : user.first_name
    'last_name' : user.last_name
  })

Upvotes: 1

user14143874
user14143874

Reputation:

I think you can use

UserProf(Modelform):

and in the views user .save() for both forms

Upvotes: 0

Related Questions