更新时间:2023-02-25 12:29:11
此外,为了在模板中获取名称,您还必须像 {{user.profile.name}}
那样访问它名称保存在配置文件模型中
Also in order to get the name in the template you have to access it like {{ user.profile.name }}
since name is saved in the Profile Model
但是但是,如果您想为个人资料模型创建表单,可以这样做
But if you want to create a form for your Profile model you can do it like this
class ProfileForm(forms.ModelForm):
class Meta:
model = Profile
fields = ("name", "description")
此外,如果您打算在同一HTML表单中同时使用UserCreationForm和ProfileForm,则应向它们添加前缀,以了解哪些数据属于哪种表单,请在此处查找操作方法 https://docs.djangoproject.com/en/1.9/ref/forms/api/#prefixes-for-forms
Also if you plan to use both the UserCreationForm and the ProfileForm both in the same HTML Form you should add a prefix to them to know which data belongs to which form, look how to do it here https://docs.djangoproject.com/en/1.9/ref/forms/api/#prefixes-for-forms
修改
def register_user(request):
#...
if request.method == "POST":
user_form = UserCreationForm(request.POST, prefix="user")
profile_form = ProfileForm(request.POST, prefix="profile")
if user_form.is_valid() and profile_form.is_valid():
user = user_form.save(commit=False)
user.save()
profile = profile_form.save(commit=False)
profile.user = user
profile.save()
return redirect('/')
else:
user_form = UserCreationForm(prefix="user")
profile_form = ProfileForm(prefix="profile")
context = {
"user_form": user_form,
"profile_form": profile_form
}
return render(request, 'register.html', context)
然后在模板中
<form action="/user/register/" method="post" id="register" autocomplete="off">
{% csrf_token %}
<div class="fieldWrapper">
{{ user_form }}
{{ profile_form }}
</div>
<input type="submit" value="Register"/>