django - 如何创建在 Django 中保存 User 和 UserProfile 对象的 View

标签 django django-models django-forms django-views django-users

我在 Django 中有两个模型:User(由 Django 预定义)和 UserProfile。两者通过外键连接。

模型.py:

class UserProfile(models.Model):
  user = models.ForeignKey(User, unique=True, related_name="connect")
  location = models.CharField(max_length=20, blank=True, null=True)

我使用 UserCreationForm(由 Django 预定义)作为用户模型,并在 forms.py 中为 UserProfile 创建了另一个表单
#UserCreationForm for User Model

class UserProfileForm(ModelForm):
  class Meta:
    model = UserProfile
    exclude = ("user", )

我在模板 registration.html 中加载这两个表单,以便网站客户可以输入有关包含在两个模型中的字段的数据(例如:用户模型中的“first_name”、“last_name”、UserProfile 模型中的“location”)。

在我的一生中,我无法弄清楚如何为这个注册表单创建一个 View 。到目前为止,我所尝试的将创建 User 对象,但它不会关联其他信息,例如相应 UserProfile 对象中的位置。谁能帮我吗?这是我目前拥有的:
def register(request):
  if request.method == 'POST':
    form1 = UserCreationForm(request.POST)
    form2 = UserProfileForm(request.POST)
    if form1.is_valid():
      #create initial entry for User object
      username = form1.cleaned_data["username"]
      password = form1.cleaned_data["password"]
      new_user = User.objects.create_user(username, password)

      # What to do here to save "location" field in a UserProfile 
      # object that corresponds with the new_user User object that 
      # we just created in the previous lines

  else:
    form1 = UserCreationForm()
    form2 = UserProfileForm()
  c = {
    'form1':UserCreationForm,
    'form2':form2,
  }
  c.update(csrf(request))
  return render_to_response("registration/register.html", c)

最佳答案

差不多好了 :)

def register(request):
    if request.method == 'POST':
        form1 = UserCreationForm(request.POST)
        form2 = UserProfileForm(request.POST)
        if form1.is_valid() and form2.is_valid():
            user = form1.save()  # save user to db
            userprofile = form2.save(commit=False)  # create profile but don't save to db
            userprofile.user = user
            userprofile.location = get_the_location_somehow()
            userprofile.save()  # save profile to db

    else:
        form1 = UserCreationForm()
         form2 = UserProfileForm()
    c = {
      'form1':form1,
      'form2':form2,
    }
    c.update(csrf(request))
    return render_to_response("registration/register.html", c)

澄清一下,form.save()创建模型的实例并将其保存到 db。 form.save(commit=False)只是创建一个实例,但不会将任何内容保存到 db。

关于django - 如何创建在 Django 中保存 User 和 UserProfile 对象的 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11924238/

相关文章:

python - 迁移中的 Django 设置

python - Django 登录重定向是否剥离了我的 url 参数?

python - Django - 同一查询中的 objects.values() 和 prefetch_related()

python - 电子邮件验证(1062, "Duplicate entry ''对于 key 'email'“)

具有同一模型的多个内联的 Django 管理

python - Django 1.10 : extend/override admin css

python - Django ForeignKey _set 在继承的模型上

django - 从 View 调用表单时排除表单字段

mysql - 如何在 Django 中创建映射表?

python - 尝试在 mac os leopard 上安装 lxml