从我的扩展用户模型向我的 UserCreationForm 添加额外的字段

Add extra fields to my UserCreationForm from my extended User model

我需要两个额外的用户数据字段,所以我遵循了官方的 django 文档 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 但这只填充了我的扩展用户模型的 user_id,即 OneToOneField 而不是两个额外的领域。 抱歉我的英语不好。

我需要 运行 但这是一个快速实施。它显然需要一些调整,但应该让你开始:

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