我想创建一个“更新用户的个人资料”页面让用户修改他们的个人资料,所以我想出了以下模型:
class Profile(models.Model):
user = models.OneToOneField(User)
nick_name = models.CharField(blank=True,max_length=100)
school = models.CharField(blank=True,max_length=100)
motto = models.CharField(blank=True,max_length=100)
class ProfileForm(ModelForm):
class Meta:
model = Profile
我的观点被设计为:
@login_required
def update_profile_view(request):
if request.method == 'POST':
user = request.user
try:
profile = user.get_profile()
except Exception:
profile = Profile.objects.create(user=user)
form = ProfileForm(request.POST)
if form.is_valid():
cd = form.cleaned_data
profile.nick_name = cd['nick_name']
profile.school = cd['school']
profile.motto = cd['motto']
profile.save()
return HttpResponseRedirect('/main_page/')
else:
form = ProfileForm()
return render(request, 'update_profile.html', {'form':form})
用户和个人资料之间的关系显然是 1to1,通过请求我可以确定当前用户。所以表单的用户字段不需要填写。不幸的是,这无法通过“form.is_valid()”测试。在调用“is_valid”之前似乎很难修改表单。为简单起见,我不想创建自己的表单类,也不想编写自定义表单验证。有没有其他方法可以解决问题?