0

I need two extra fields for the user data so I followed the official django docs Extending the existing User model, the admin form for users works fine but I have a UserCreationForm and I want to add the two extra fields in that form too, already tried to use two forms, the UserCreationForm and the form for my extended user model but I can't get the id of the UserCreationForm to fill the user_id of my extended user model so I search how to use a signal to do that like the django docs recommend and find this Django Signals: create a Profile instance when a new user is created but that only fill the user_id of my extended user model that is the OneToOneField but not the two extra fields. sorry for my bad english.

M. Gar
  • 889
  • 4
  • 16
  • 33
  • Have you tried using `ModelForm` for your extended model? https://docs.djangoproject.com/en/1.9/topics/forms/modelforms/ – Shang Wang Jan 12 '16 at 23:06
  • I tried this too http://stackoverflow.com/questions/11918355/how-to-extend-usercreationform-with-fields-from-userprofile but don't save the extra fields – M. Gar Jan 12 '16 at 23:08
  • No, but how can I use the ModelForm for my extended model to save the extra data in the UserCreationForm? – M. Gar Jan 12 '16 at 23:12

1 Answers1

0

I need to run but here's a quick implementation. It needs some tweaks apparently but should get you started:

# this is your model form for extended OneOnOne with user
class ExtendedForm(forms.ModelForm):
    model = ExtendedModel
    # temporary exclude user field to pass the validation
    exclude = ('user')

def create_user(request):
    user_form = UserForm(request.POST or None)
    extra_form = ExtendedForm(request.POST or None)

    if user_form.is_valid() and extra_form.is_valid():
        # create a new user first
        new_user = user_form.save()
        # create an object in memory but not save it
        new_extended_obj = extra_form.save(commit=False)
        # assign the user to the extended obj
        new_extended_obj.user = new_user
        # write to database
        new_extended_obj.save()
Shang Wang
  • 24,909
  • 20
  • 73
  • 94