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

时间:2022-07-08 19:20:40

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.

我需要两个额外的用户数据字段,所以我按照官方的django文档扩展现有的用户模型,用户的管理表单工作正常,但我有一个UserCreationForm,我想在该表单中添加两个额外的字段,已经尝试过使用两个表单,UserCreationForm和我的扩展用户模型的表单,但我无法获取UserCreationForm的ID来填充我的扩展用户模型的user_id所以我搜索如何使用信号像django文档那样做推荐并找到这个Django Signals:在创建新用户时创建一个Profile实例,但是只填充我的扩展用户模型的user_id,即OneToOneField而不是两个额外的字段。对不起,我的英语不好。

1 个解决方案

#1


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

#1


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