In Django how can I create a user and a user profile at the same time from a single form submission

大兔子大兔子 提交于 2019-12-03 04:56:14

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']))

There's a similar solution I found here: http://sontek.net/blog/detail/extending-the-django-user-model

Basically you just extend the default form UserCreationForm but keeping the same name. By doing it like this you dont have to add any new views or anything like that, it works seamlessly with the way Django's docs tell you to do UserProfiles.

Frankly, I don't understand why they explain how to add the fields to the admin page, and then don't tell you how to actually use those fields anywhere.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!