无法使用扩展的用户模型正确保存数据

时间:2019-03-27 15:22:11

标签: django django-models

将身份验证用户扩展到个人资料

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的其他数据,反之亦然。

1 个答案:

答案 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上)。