@render_to('edit_operation.html')
def edit_operation(request, pk):
from forms import OpBaseForm, OperationForm
from django.forms.models import inlineformset_factory
op = Operation.objects.get(pk=pk)
OpBaseFormSet = inlineformset_factory(Operation, OpBase, form=OpBaseForm, extra=5, )
if request.method == "POST":
form = OperationForm(request.POST, instance=op)
formset = OpBaseFormSet(request.POST, instance=op)
if formset.is_valid() and form.is_valid():
form.save()
formset.save() #error here
return HttpResponseRedirect( op.get_absolute_url() )
else:
form = OperationForm(instance=op)
formset = OpBaseFormSet(instance=op)
return {'operation': op, 'opform': form, 'formset': formset}
这看起来非常简单,但每当我尝试提交数据(甚至是未更改的数据)时,我都会收到此错误:
Environment: Request Method: POST Request URL: http://localhost:8000/edit/operation/1/ Django Version: 1.0.2 final Python Version: 2.6.2 Installed Applications: ['main', 'django_extensions', 'django.contrib.comments', 'django.contrib.admindocs', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.gis', 'django.contrib.humanize', 'registration'] Installed Middleware: ('django.middleware.common.CommonMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware') Traceback: File "/usr/lib/python2.6/dist-packages/django/core/handlers/base.py" in get_response 86. response = callback(request, *callback_args, **callback_kwargs) File "/usr/lib/python2.6/dist-packages/annoying/decorators.py" in wrapper 55. output = function(request, *args, **kwargs) File "/home/chris/Websites/jobmap/main/views.py" in edit_operation 68. formset.save() File "/usr/lib/python2.6/dist-packages/django/forms/models.py" in save 389. return self.save_existing_objects(commit) + self.save_new_objects(commit) File "/usr/lib/python2.6/dist-packages/django/forms/models.py" in save_existing_objects 403. obj = existing_objects[form.cleaned_data[self._pk_field.name]] Exception Type: KeyError at /edit/operation/1/ Exception Value: None
任何人都知道导致此错误的原因是什么?如果formset中有错误,那么formset.is_valid()
做什么是'真'?任何人至少对如何调试这个有任何想法,以找到什么问题?单独使用时,两种表单都可以正常工作,我的模板中有{{formset.management_form}}
。
答案 0 :(得分:1)
只是一个快速的猜测...是你的OpBaseForm除了模型pk?或者,您是否错过了模板中的pk字段?换句话说,如果你自己布置字段,你仍然需要包含pk字段,即使它是隐藏的。