渲染嵌入式formset management_form时,django mongodbforms异常

时间:2014-08-18 20:40:48

标签: python django mongoengine

我正在使用mongodbforms连接到我的django项目中的MongoDB。我想使用嵌入式formset来填充嵌入字段列表。当我只尝试在formset中渲染一个表单时,一切正常。但是,当我设置extra=3并尝试为嵌入的formset渲染management_form时,我得到一个异常。 这是我的model.py

from mongoengine import *
from MongoNotes.settings import DBNAME

connect(DBNAME)

class CollectionField(EmbeddedDocument):
    name = StringField(max_length=120, required=True)

class Collection(Document):
    name = StringField(max_length=120, required=True)
    collection_fields = ListField(EmbeddedDocumentField(CollectionField))

这是我的表单和表单集(请注意extra=3 - 这导致了一个execption:

# coding=utf-8
from crispy_forms.helper import FormHelper
from mongodbforms import embeddedformset_factory, EmbeddedDocumentForm
from MongoNotes.apps.Notes.models import CollectionField, Collection

class FieldForm(EmbeddedDocumentForm):
    class Meta:
        document = CollectionField
        embedded_field_name = 'collection_fields'

        fields = ['name',]

    def __init__(self, *args, **kwargs):
        super(FieldForm, self).__init__(*args, **kwargs)

        self.helper = FormHelper()
        self.helper.form_id = 'collection_field_form'
        self.helper.form_tag = False

FieldFormSet = embeddedformset_factory(CollectionField, Collection, form=FieldForm, extra=3)

这是一个模板:

<!DOCTYPE html>
<html>
    <head>
    </head>
    <body>
        <h1>Add collection</h1>
        <form method="post" class="form-horizontal">
            {{ field_formset.management_form }}
        </form>
    </body>
</html>

完整性在这里是我的观点:

# coding=utf-8
from django.views.generic import TemplateView
from MongoNotes.apps.Notes.forms import FieldFormSet
from models import Collection

class AddCollectionView(TemplateView):
    template_name = 'add_collection.html'

    def get_context_data(self, **kwargs):
        context = super(AddCollectionView, self).get_context_data(**kwargs)
        context['field_formset'] = FieldFormSet(prefix='field', parent_document=Collection())
        return context
运行这个给了我一个例外:

Environment:

Request Method: GET
Request URL: http://127.0.0.1:8000/

Django Version: 1.6.5
Python Version: 2.7.3
Installed Applications:
('django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'django.contrib.admin',
 'MongoNotes.apps.Notes',
 'crispy_forms')
Installed Middleware:
('django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware')

Template error:
In template C:\projects\mongodbforms_error\MongoNotes\apps\Notes\templates\add_collection.html, error at line 8
   list index out of range
   1 : <!DOCTYPE html>
   2 : <html>
   3 :     <head>
   4 :     </head>
   5 :     <body>
   6 :         <h1>Add collection</h1>
   7 :         <form method="post" class="form-horizontal">
   8 :              {{ field_formset.management_form }} 
   9 :         </form>
   10 :     </body>
   11 : </html>

Traceback:
File "C:\(...)\mongodbforms_error\lib\site-packages\django\core\handlers\base.py" in get_response
  137.                 response = response.render()
File "C:\(...)\mongodbforms_error\lib\site-packages\django\template\response.py" in render
  105.             self.content = self.rendered_content
File "C:\(...)\mongodbforms_error\lib\site-packages\django\template\response.py" in rendered_content
  82.         content = template.render(context)
File "C:\(...)\mongodbforms_error\lib\site-packages\django\template\base.py" in render
  140.             return self._render(context)
File "C:\(...)\mongodbforms_error\lib\site-packages\django\template\base.py" in _render
  134.         return self.nodelist.render(context)
File "C:\(...)\mongodbforms_error\lib\site-packages\django\template\base.py" in render
  840.                 bit = self.render_node(node, context)
File "C:\(...)\mongodbforms_error\lib\site-packages\django\template\debug.py" in render_node
  78.             return node.render(context)
File "C:\(...)\mongodbforms_error\lib\site-packages\django\template\debug.py" in render
  88.             output = self.filter_expression.resolve(context)
File "C:\(...)\mongodbforms_error\lib\site-packages\django\template\base.py" in resolve
  585.                 obj = self.var.resolve(context)
File "C:\(...)\mongodbforms_error\lib\site-packages\django\template\base.py" in resolve
  735.             value = self._resolve_lookup(context)
File "C:\(...)\mongodbforms_error\lib\site-packages\django\template\base.py" in _resolve_lookup
  765.                     current = current[bit]
File "C:\(...)\mongodbforms_error\lib\site-packages\django\forms\formsets.py" in __getitem__
  69.         return self.forms[index]
File "C:\(...)\mongodbforms_error\lib\site-packages\django\utils\functional.py" in __get__
  49.         res = instance.__dict__[self.func.__name__] = self.func(instance)
File "C:\(...)\mongodbforms_error\lib\site-packages\django\forms\formsets.py" in forms
  133.         forms = [self._construct_form(i) for i in xrange(self.total_form_count())]
File "C:\(...)\mongodbforms_error\lib\site-packages\mongodbforms\documents.py" in _construct_form
  930.         form = super(EmbeddedDocumentFormSet, self)._construct_form(i, **defaults)
File "C:\(...)\mongodbforms_error\lib\site-packages\django\forms\formsets.py" in _construct_form
  157.         form = self.form(**defaults)
File "C:\projects\mongodbforms_error\MongoNotes\apps\Notes\forms.py" in __init__
  15.         super(FieldForm, self).__init__(*args, **kwargs)
File "C:\(...)\mongodbforms_error\lib\site-packages\mongodbforms\documents.py" in __init__
  548.                 instance = getattr(parent_document, self._meta.embedded_field)[position]
File "C:\(...)\mongodbforms_error\lib\site-packages\mongoengine\base\datastructures.py" in __getitem__
  96.         value = super(BaseList, self).__getitem__(*args, **kwargs)

Exception Type: IndexError at /
Exception Value: list index out of range

我自己试图对此进行调试,但我对Python的熟练程度不足以找出问题的根源。

1 个答案:

答案 0 :(得分:0)

Django MongoDBForms不再由其原始创建者维护,现在已经分散成一堆乱七八糟的东西。我在其中一个上对嵌入式文档formset代码做了一些小修复。我不确定他们是否会解决您的问题,但可能有用的是使用项目中最新更新的一个而不是原始的。

我不能建议一个人专门解决你的问题,但我注意到这个fork已经采取了我所做的更改并进一步推进了它们。 https://github.com/baffolobill/django-mongodbforms