1

我有一个与使用多表模型继承的模型相关的表单集。提交表单时出现以下错误:

MultiValueDictKeyError

"Key 'form-0-mediaitem_ptr' not found in <QueryDict: {u'form-0-caption': 
[u'asfdasda'], u'form-MAX_NUM_FORMS': [u''], u'form-TOTAL_FORMS': [u'1'], u'form-
INITIAL_FORMS': [u'1'], u'img_info_submitted': [u'save to library'], 
u'csrfmiddlewaretoken': .......

以下是涉及的模型:

class MediaItem(models.Model):
    '''
    Parent class for all media items (ImageItem, VideoItem,
    AudioItem, and TextItem).
    '''
    user = models.ForeignKey(User)
    upload_date = models.DateTimeField(auto_now_add = True)
    last_modified = models.DateTimeField(auto_now = True)

class ImageItem(MediaItem):        
    original_img = models.ImageField(upload_to = img_get_file_path)
    large_img = models.ImageField(upload_to = img_get_file_path)
    thumbnail_img = models.OneToOneField(ItemThumbnail)
    caption = models.CharField(max_length = 1000,
                               blank = True)

这是用于表单集的表单:

class ImageInfoForm(forms.ModelForm):
    class Meta:
        model = ImageItem

    def __init__(self, *args, **kwargs):
        super(ImageInfoForm, self).__init__(*args, **kwargs)
        self.fields['caption'].widget = forms.Textarea(attrs = {'placeholder': 'caption'})

    caption = forms.CharField(widget = forms.Textarea(attrs = {'placeholder': 'caption'}),
                              max_length = 1000,
                              required = True)

我尝试在视图中构建表单集,如下所示:

ImageInfoFormset = modelformset_factory(ImageItem,
                                        form = ImageInfoForm,
                                        fields=['caption',
                                                'mediaitem_ptr'],
                                        extra = 0)

而且,我也试过这样:

ImageInfoFormset = modelformset_factory(ImageItem,
                                        form = ImageInfoForm,
                                        extra = 0)

在模板中,我确保在循环中使用整个{{form}}标签 。{% for form in formset %}

看到Erik对他自己的问题的回答,How to debug a Django MultiValueDictKeyError on Formset POST,我将其更改ImageForm为以下内容,但没有运气:-(

class ImageInfoForm(forms.ModelForm):
    class Meta:
        model = ImageItem
        fields = (
            'mediaitem_ptr',
            'caption')

    def __init__(self, *args, **kwargs):
        super(ImageInfoForm, self).__init__(*args, **kwargs)
        self.fields['caption'].widget = forms.Textarea(attrs = {'placeholder': 'caption'})

    caption = forms.CharField(widget = forms.Textarea(attrs = {'placeholder': 'caption'}),
                              max_length = 1000,
                              required = True)

有谁知道如何解决这一问题?我知道指向父模型的指针必须在表单中,以便更新正确的实例,但我该如何实现呢?谢谢!

4

1 回答 1

1

我从您的示例中制作了一个示例应用程序,当我提交表单时,它按预期工作,没有收到您提到的错误。

在您的情况下,您应该mediaitem_ptr在使用{{ form }}. 在您引用的答案中,作者正在单独呈现字段,在这种情况下,您需要手动包含指针输入字段。

于 2013-06-18T07:08:50.580 回答