5

我在 Django 中有两个模型:用户(由 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”)。

对于我的生活,我无法弄清楚如何为此注册表单创建视图。到目前为止我所尝试的将创建 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)
4

1 回答 1

3

差不多好了 :)

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。

于 2012-08-12T17:34:54.517 回答