我在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", )
我将这两个表单加载到一个模板中,注册.html,因此网站客户可以输入有关两个模型中包含的字段的数据(例如:"first_name"、"用户模型中的last_name",用户配置文件模型中的"位置")。
对于我的一生,我不知道如何为此注册表创建视图。到目前为止,我尝试的方法将创建 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()
创建模型的实例并将其保存到数据库。 form.save(commit=False)
只是创建一个实例,但不会将任何内容保存到数据库。