Login

Combine ProfileForm an UserForm in one.

Author:
sarg
Posted:
June 24, 2010
Language:
Python
Version:
Not specified
Tags:
forms user profile
Score:
5 (after 6 ratings)

Using this method you can combine form for standart django.contrib.auth.models.User model and for your project profile model. As now, ProfileForm can be used as usual, and it will also contain UserForm fields.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
class UserForm(forms.ModelForm):
    class Meta:
        model = User
        fields = ('first_name', 'last_name', 'email')

class ProfileForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        # magic 
        self.user = kwargs['instance'].user
        user_kwargs = kwargs.copy()
        user_kwargs['instance'] = self.user
        self.uf = UserForm(*args, **user_kwargs)
        # magic end 

        super(ProfileForm, self).__init__(*args, **kwargs)

        self.fields.update(self.uf.fields)
        self.initial.update(self.uf.initial)
         
        # define fields order if needed
        self.fields.keyOrder = (
            'last_name',
            'first_name',
            'second_name',

            'birthdate',
            'position',
            'contacts',

            'about',
        )

    def save(self, *args, **kwargs):
        # save both forms   
        self.uf.save(*args, **kwargs)
        return super(ProfileForm, self).save(*args, **kwargs)

    class Meta:
        model = Profile

More like this

  1. Handles Inline Formsets and also "in-standard-way" normal forms by sebnapi 3 years ago
  2. create and authenticate an anonymous user by chr15m 5 years, 5 months ago
  3. Access transparently the user profile information by gsakkis 4 years, 6 months ago
  4. Extended Profiling and Timing Middleware using cProfile by dstryke 1 year, 4 months ago
  5. Django profiler by dogada 7 years, 3 months ago

Comments

Please login first before commenting.