我在Django中有两个模型:User(由Django预定义)和UserProfile。这两个是通过外键连接的。
models.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)
答案 0 :(得分: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()
创建了Model的一个实例并将其保存到db。 form.save(commit=False)
只创建一个实例,但不会向db保存任何内容。