我使用以下模板收集用户信息:
<div class="row text-center vertical-middle-sm">
<h1>Profile</h1>
<div class="row">
<div class="col-md-6">
<div class="row">
<div class="col-md-4 text-right"><span>Username:</span></div>
<div class="col-md-8 text-left"><span>{{ user.username }}</span></div>
</div>
<div class="row">
<div class="col-md-4 text-right"><span>Gender:</span></div>
<div class="col-md-8 text-left"><span>{{ user_profile.get_gender_display }}</span></div>
</div>
视图中,初始化数据有很多困难:
else:
user_form = UserForm(instance=request.user)
user_profile_form = UserProfileForm(
initial={'birthday':user_profile.birthday,
'telephone':user_profile.telephone,
'school':user_profile.school,
'company':user_profile.company,
'profession':user_profile.profession,
'country':user_profile.country,
'about_me':user_profile.about_me,
})
context = {"user_form":user_form,
"user_profile_form":user_profile_form,}
return render(request, "account/edit_profile.html", context)
如何重构较短的initial={}
?
答案 0 :(得分:1)
您应该像使用UserForm一样使用initial
参数。
user_profile_form = UserProfileForm(instance=request.user.profile)