将身份验证用户扩展到个人资料
class Profile(models.Model):
user = models.OneToOneField(User, null=True, on_delete=models.CASCADE)
age = models.IntegerField(default=18)
university = models.CharField(max_length=100, default='')
department = models.CharField(max_length=50, default='')
Views.py
def register(request):
if request.method == 'POST':
form = UserRegisterForm(request.POST)
profile_form = ProfileForm(request.POST)
if form.is_valid() and profile_form.is_valid():
try:
with transaction.atomic():
form.save()
profile_form.save()
except DatabaseError:
pass
username = form.cleaned_data.get('username')
messages.success(request, f'Account Created for {username}!')
return redirect('jmiforums:homepage')
else:
form = UserRegisterForm()
profile_form = ProfileForm()
return render(request, 'jmiforums/register.html', {"form":form, "profile_form": profile_form,})`
注册表格
<form method="POST">
{% csrf_token %}
<fieldset class="form-group">
<legend class="border-bottom mb-4">JMI Forum</legend>
{{ form.as_p }}
{{ profile_form.as_p }}
</fieldset>
<div class="form-group">
<button class="btn btn-outline-info" type="submit">Sign up</button>
</div>
</form>
数据每次在Profile表中保存两次,一次连接了User,但没有来自Profile Model的其他数据,反之亦然。
答案 0 :(得分:0)
您可能不应该在没有Profile
的情况下允许user
(删除null=True
)。假设您的UserRegisterForm
仅保存了User
模型,而您的ProfileForm
仅适用于Profile
模型:
if form.is_valid() and profile_form.is_valid():
user = form.save()
profile = profile_form.save(commit=False)
profile.user = user
profile.save()
您使用commit=False
创建实例而不保存实例,然后将关系添加到user
,然后保存配置文件。另外,还要确保在创建Profile
时没有创建空的User
(例如,如Django文档所述,如果您将post_save
处理程序钩在User
上)。