我正在尝试使用与用于创建用户帐户的表单相同的表单更新自定义用户的字段。用户帐户工作正常,form.is_valid()返回true,导致保存和重定向,但是在下面的代码中,重定向永远不会发生,并且使用提交按钮时不会保存表单上更新的字段。我觉得我错过了一些简单但却无法看到的东西。下面的视图是否有理由不保存表单上更新的数据?
由于
def update_user(request):
user = Customer.objects.get(pk=request.user.id)
form = CustomerForm(instance=user)
if request.method == 'POST':
form = CustomerForm(request.POST)
if form.is_valid():
form.save()
return HttpResponseRedirect('success.html')
args = {}
args.update(csrf(request))
args['form'] = form
return render_to_response('update.html', args)
答案 0 :(得分:1)
当表单无效时,您是否尝试打印form._errors?这是调试此类问题的好方法。这里有固定代码:
def update_user(request):
user = Customer.objects.get(pk=request.user.id)
form = CustomerForm(instance=user)
if request.method == 'POST':
form = CustomerForm(request.POST, instance=user) # HERE
if form.is_valid():
form.save()
return HttpResponseRedirect('success.html')
args = {}
args.update(csrf(request))
args['form'] = form
return render_to_response('update.html', args)
此外,您可以替换此代码:
form = CustomerForm(instance=user)
if request.method == 'POST':
form = CustomerForm(request.POST, instance=user) # HERE
if form.is_valid():
form.save()
return HttpResponseRedirect('success.html')
使用这个(工作原理相同):
form = CustomerForm(request.POST or None, instance=user)
if form.is_valid():
form.save()
return HttpResponseRedirect('success.html')