M. Gar
M. Gar

Reputation: 887

Add extra fields to my UserCreationForm from my extended User model

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.

Upvotes: 0

Views: 723

Answers (1)

Shang Wang
Shang Wang

Reputation: 25539

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()

Upvotes: 0

Related Questions