更新时间:2023-12-02 09:02:46
制作两种模型表单,一种用于User
模型,一种用于UserProfile
模型.
Make two model forms, one for the User
model and one for the UserProfile
model.
class UserForm(django.forms.ModelForm):
class Meta:
model = User
class UserProfileForm(django.forms.ModelForm):
class Meta:
model = UserProfile
exclude = ['user']
给它们加上前缀并将它们一起显示在同一个 HTML 表单元素中.在视图中,在保存 User 和 UserProfile 之前检查两者是否有效.
Give them prefixes and display them together in the same HTML form element. In the view, check that both are valid before you save the User and then the UserProfile.
def register(request):
if request.method == 'POST':
uf = UserForm(request.POST, prefix='user')
upf = UserProfileForm(request.POST, prefix='userprofile')
if uf.is_valid() * upf.is_valid():
user = uf.save()
userprofile = upf.save(commit=False)
userprofile.user = user
userprofile.save()
return django.http.HttpResponseRedirect(…something…)
else:
uf = UserForm(prefix='user')
upf = UserProfileForm(prefix='userprofile')
return django.shortcuts.render_to_response('register.html',
dict(userform=uf,
userprofileform=upf),
context_instance=django.template.RequestContext(request))
在 register.html
中:
<form method="POST" action="">
{% csrf_token %}
{{userform}}
{{userprofileform}}
<input type="submit">
</form>