没有什么比不理解为什么会起作用更糟糕的了。几天前我问了这个问题并想出了一个解决方法,但我不知道它为什么有效:
如何在 Formset POST 上调试 Django MultiValueDictKeyError。
为什么表单集需要一个指向表单集模型表单模型超类的指针字段引用?我还有其他类似的表单集没有。
为了使这成为一个独立的问题,以下是详细信息:
当我发布我的表单集时,我得到一个 MultiValueDictKeyError。具体来说:
MultiValueDictKeyError at /core/customers/1/update/documents/
"Key u'documents-0-attachment_ptr' not found in <QueryDict: {u'documents-1-last_modified_date': [u''], u'documents-1-name': [u''], u'documents-MAX_NUM_FORMS': [u''], u'documents-0-attachment_file': [u''], u'documents-INITIAL_FORMS': [u'1'], u'documents-1-document_type': [u''], u'documents-0-notes': [u''], u'documents-1-notes': [u''], u'submit': [u'Submit changes'], u'documents-0-DELETE': [u'on'], u'documents-1-attachment_file': [u''], u'documents-0-document_type': [u''], u'documents-TOTAL_FORMS': [u'2'], u'documents-0-name': [u'test'], u'documents-1-creation_date': [u''], u'documents-0-creation_date': [u'2012-12-01 23:41:48'], u'csrfmiddlewaretoken': [u'NCQ15jA7erX5dAbx20Scr3gWxgaTn3Iq', u'NCQ15jA7erX5dAbx20Scr3gWxgaTn3Iq', u'NCQ15jA7erX5dAbx20Scr3gWxgaTn3Iq'], u'documents-0-last_modified_date': [u'2012-12-01 23:41:48']}>"
documents-0-attachment_ptr
关键部分是 Django在 post 数据中寻找密钥。这很令人困惑——文档是附件的子类。所有其他帖子数据都符合预期。为什么 Django 在我的表单集中需要指针数据?
这是表单集中使用的表单:
class DocumentInlineForm(forms.ModelForm): # pylint: disable=R0924
attachment_file = forms.FileField(widget=NoDirectoryClearableFileInput)
notes = forms.CharField(
required=False,
widget=forms.Textarea(attrs={'rows': 2,}),
)
helper = DocumentInlineFormHelper()
class Meta: # pylint: disable=W0232,R0903
fields = (
'attachment_file',
'creation_date',
'document_type',
'last_modified_date',
'name',
'notes',
)
model = Document
这是文档模型:
"""
Handles document model definitions.
"""
from django.db import models
from eee_core.models.attachments import Attachment
from django.db.models.signals import pre_save
from datetime import datetime
from django.utils.timezone import utc
class Document(Attachment):
"""
A document is an attachment with additional meta data.
"""
creation_date = models.DateTimeField(
blank=True,
null=True,
)
document_type = models.CharField(
blank=True,
choices=(
('CONTRACT', 'Contract'),
('INVOICE', 'Invoice'),
('FACILITY', 'Facility change form'),
('LOA', 'Letter of authorization'),
('USAGE', 'Usage history document'),
('OTHER', 'Other'),
),
default=None,
null=True,
max_length=8,
)
last_modified_date = models.DateTimeField(
blank=True,
null=True,
)
notes = models.TextField(
blank=True,
null=True,
)
class Meta(Attachment.Meta): # pylint: disable=W0232,R0903
"""
Sets meta fields for model.
"""
app_label = 'core'
def __str__(self):
return unicode(self).encode('utf-8')
def __unicode__(self):
return unicode(self.name)
def pre_save_callback(sender, instance, *args, **kwargs): # pylint: disable=W0613
if not isinstance(instance, Document):
return
if not instance.creation_date:
instance.creation_date = datetime.utcnow().replace(tzinfo=utc)
instance.last_modified_date = datetime.utcnow().replace(tzinfo=utc)
pre_save.connect(pre_save_callback, dispatch_uid='document_pre_save')
附加信息:
奇怪的是,表单集的初始帖子工作正常。只有在更新帖子上——当表单集中有初始表单时——当我收到这个错误时。当我尝试从表单集中删除表单时也会发生这种情况。
此外,该表单集是使用 django 脆表单的通用内联表单集。
更新
有一个使用模板代码的请求。这是简化版:
{% load crispy_forms_tags %}
{% load url from future %}
<form action="" method="post" enctype="multipart/form-data">
{{ formset.management_form }}
{% for subform in formset.forms %}
{{ subform.id }}
{% crispy subform %}
{% endfor %}
<div class="btn-toolbar">
<input class='btn btn-primary' type="submit" name="submit" value="Submit changes" />
</div>
</form>
attachment_ptr
我通过添加到表单的字段列表来停止此错误。现在DocumentInlineForm
也是:
class DocumentInlineForm(forms.ModelForm): # pylint: disable=R0924
attachment_file = forms.FileField(widget=NoDirectoryClearableFileInput)
notes = forms.CharField(
required=False,
widget=forms.Textarea(attrs={'rows': 2,}),
)
helper = DocumentInlineFormHelper()
class Meta: # pylint: disable=W0232,R0903
fields = (
'attachment_ptr',
'attachment_file',
'creation_date',
'document_type',
'last_modified_date',
'name',
'notes',
)
model = Document
也许这是我以前不知道的事情,但是 Django 是否要求您在所有使用子类模型的形式中提供指向超类的指针?这让我很惊讶。