在Django中,如何通过一次表单提交同时创建用户和用户个人资料 [英] In Django how can I create a user and a user profile at the same time from a single form submission

查看:72
本文介绍了在Django中,如何通过一次表单提交同时创建用户和用户个人资料的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用UserCreationForm的扩展版通过我自己的模板添加用户,效果很好。

I am using extended version of the UserCreationForm to add users via my own template, which is working well.

我也想将其包括在内相同的表单模板,这是我的用户个人资料模型中的自定义字段,因此创建用户时,也会创建带有我的自定义字段的用户个人资料。

I would also like to include, as part of the same form template, a custom field from my userprofile model, so that when the user is created a user profile with my custom field would also be created.

我的处理方法一直使用两种形式,并使用一个提交按钮将它们组合在一个模板中。

My approach to this has been to use two forms and combine them in one template with a single submit button.

该窗体完全按照我的要求显示,并正确返回验证错误,但是可以预料的是,保存到数据库时,窗体会掉落。当我在用户表单上调用save()时,将创建用户,但是,当我尝试保存用户配置文件表单时,它会引发错误,因为该用户尚不存在,因此它没有用户关联。

The form displays exactly as I wanted, and returns validation errors correctly, but predictably it falls down when it comes to saving to the database. When I call save() on the user form the user is created, but of course when I try to save the userprofile form it throws an error because the user doesn't yet exist so it has not user associated to it.

尽管我认为我理解问题的原因,但是如何解决却无所适从,我什至不确定我采用的方法是否正确。

Although I think I understand the cause of my problem, I am at a loss as to how to fix it, I am not even sure if the approach that I have taken is correct.

我已经在下面包括了我的所有代码,包括模型,表单和视图,以防万一这有助于任何人更好地理解我的工作方式: / p>

UserProfile类(models.py)



I have included all my code below including the model as well as the forms and the view just in case this helps anyone to better understand what I am trying to do:

LEVEL = (
    ('admin', 'administrator'),
    ('team', 'team leader'),
    ('member', 'team member'),
)

class UserProfile(models.Model):
    user = models.ForeignKey(User, unique=True)
    level = models.CharField(choices=LEVEL, max_length=20)



UserCreationForm和UserProfileForm类(forms.py)



UserCreationForm and UserProfileForm classes (forms.py)

class UserCreationFormExtended(UserCreationForm): 
    def __init__(self, *args, **kwargs): 
        super(UserCreationFormExtended, self).__init__(*args, **kwargs) 
        self.fields['first_name'].required = True
        self.fields['last_name'].required = True

    class Meta: 
       model = User 
       fields = ('username', 'email', 'first_name', 'last_name') 


class UserProfileForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        super(UserProfileForm, self).__init__(*args, **kwargs)  

         self.fields["level"].choices = ( ('admin', 'administrator'), ('team', 'team leader'), ('member', 'team member') )

    class Meta:
        model = UserProfile



use_add视图(views.py)



use_add view (views.py)

def user_add(request):

    if request.method == 'POST':
        uform = UserCreationFormExtended(request.POST)
        pform = UserProfileForm(request.POST)

        if uform.is_valid():

            uform.save()
            pform.save()

            return render_to_response('user/add_success.html', context_instance=RequestContext(request))

        else:
            return render_to_response('user/add.html', { 'uform' : uform, 'pform' : pform }, context_instance=RequestContext(request))

    else:
        uform = UserCreationFormExtended()
        pform = UserProfileForm()

        return render_to_response('user/add.html', { 'uform' : uform, 'pform' : pform }, context_instance=RequestContext(request))


推荐答案

首先,添加 exclude =('user', )到ProfileForm的Meta类。然后,在您看来:

First, add exclude = ('user',) to the Meta class for ProfileForm. Then, in your view:

user_valid = uform.is_valid()
profile_valid = pform.is_valid()
if user_valid and profile_valid:
    user = uform.save()
    profile = pform.save(commit=False)
    profile.user = user
    profile.save()

尽管在我看来,由于您在个人资料表单上只有一个字段,所以一种更简单的方法这样做是完全忘记了该表单,只需将字段添加到用户表单中即可:

Although it occurs to me that since you only have one field on the profile form, an easier way to do it is to forget that form completely, and just add the field to the user form:

class UserCreationFormExtended(UserCreationForm): 
    level = forms.ChoiceField(choices=LEVEL, max_length=20)
    ... etc...

if uform.is_valid():
    user = uform.save()
    profile = Profile.objects.create(user=user, level=uform.cleaned_data['level']))

这篇关于在Django中,如何通过一次表单提交同时创建用户和用户个人资料的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆