我的意图是使用 Django 的 User 模型和 UserProfile 模型(基本上添加有关用户的详细信息/字段)创建用户配置文件。然后我想创建一个注册表单,要求填写包含在用户模型和用户配置文件模型中的字段(即两个模型的字段的单个表单)。
现在发生的事情是在将必要的数据输入我的表单后,视图通过并且服务器确实创建了一个 User 对象,甚至将它链接到一个 UserProfile 对象(据我所知,这种链接发生是因为在models.py 类)。但是,没有添加有关 UserProfile 的信息(在本例中为“位置”字段),而且对于我的生活,我无法弄清楚为什么。
我有以下models.py
class UserProfile(models.Model):
# This field is required.
user = models.ForeignKey(User, unique=True, related_name="connector")
location = models.CharField(max_length=20, blank=True, null=True)
def create_user_profile(sender, instance, created, **kwargs):
if created:
UserProfile.objects.create(user=instance)
post_save.connect(create_user_profile, sender=User)
我有以下forms.py(其中UserForm基于Django定义的用户模型)
class UserForm(ModelForm):
class Meta:
model = User
class UserProfileForm(ModelForm):
class Meta:
model = UserProfile
我有以下views.py
@csrf_protect
def register(request):
if request.method == 'POST':
form1 = UserForm(request.POST)
form2 = UserProfileForm(request.POST)
if form1.is_valid() and form2.is_valid():
#create initial entry for user
username = form1.cleaned_data["username"]
password = form1.cleaned_data["password"]
new_user = User.objects.create_user(username, password)
new_user.save()
#create entry for UserProfile (extension of new_user object)
profile = form2.save(commit = False)
profile.user = new_user
profile.save()
return HttpResponseRedirect("/books/")
else:
form1 = UserForm()
form2 = UserProfileForm()
c = {
'form1':form1,
'form2':form2,
}
c.update(csrf(request))
return render_to_response("registration/register.html", c)
我有以下 register.html
<form action="/accounts/register/" method="post">{% csrf_token %}
<p style="color:red"> {{form.username.errors}}</p>
{{ form1.as_p }}
{{ form2.as_p }}
<input type="submit" value="Create the account">
</form>
谁能看到我做错了什么?有一个更好的方法吗?提前致谢!