【发布时间】:2012-08-09 02:07:02
【问题描述】:
我在 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)
【问题讨论】:
标签: django django-models django-forms django-views django-users