我的意图是使用Django的User模型和UserProfile模型(基本上添加有关用户的详细信息/字段)创建用户配置文件。然后,我想创建一个注册表单,要求填写用户模型和UserProfile模型中包含的字段(即,来自两个模型的字段的单个表单)。如何在Django中的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(其中用户窗体是基于由Django的定义的用户模型)
class UserForm(ModelForm):
class Meta:
model = User
class UserProfileForm(ModelForm):
class Meta:
model = UserProfile
我有以下的观点的.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>
任何人都可以看到我做错了什么吗?有一个更好的方法吗?提前致谢!
POST数据包含这些变量的值。你在问什么? – goelv 2012-08-12 15:49:58
此外,注册页面现在要求我选择一个用户以验证(对于表单2)。然而,这个用户是我试图通过表单创建的用户(即它没有创建年份)。我可以设置唯一的可选外键吗? – goelv 2012-08-12 16:01:40
可选且唯一。这些都是悖论。请尝试我的上述代码并通知我 – Bartanix 2012-08-18 23:11:18