尝试使用 Django MongoDBForms 替换 ModelForms 但在保存表单实例时出现这个非常奇怪的错误。
在 save() 期间,mongoengine.Document 检查 MongoDBForm 包装的 _meta 字典中的 cascade 关键字。
MongoDBForm 然后从 getitem 抛出一个KeyError
它在寻找什么级联键?!
我做错了吗?
Request Method: POST
Request URL: http://localhost:8000/add_item/Books
Django Version: 1.4.2
Exception Type: KeyError
Exception Value:
0
Exception Location: /Users/holografix/.virtualenvs/troca/lib/python2.7/site-packages/mongodbforms/documentoptions.py in __getitem__, line 171
Python Executable: /Users/holografix/.virtualenvs/troca/bin/python
Python Version: 2.7.3
来自 models.py 的模型
class GenericItem(Document):
owner_id = IntField(required=True)
title = StringField(max_length=70, required=True)
description = StringField(max_length=140, required=True)
value = IntField()
location = GeoPointField()
offers = ListField(EmbeddedDocumentField('Offer'))
def __unicode__(self):
return self.title
class Meta:
abstract = False
app_label = 'troca_app'
db_table = 'generic_item'
allow_inheritance = True
等效于 forms.py 的 ModelForm
class ModelFormGenericItem(DocumentForm):
class Meta:
document = GenericItem
fields = ('title', 'value', 'description')
查看我处理表单的位置
@login_required
def add_item(request, category):
if request.method == 'POST':
if category == 'Muffins':
form = ModelFormMuffin(request.POST)
elif category == 'Cameras':
form = ModelFormCameras(request.POST)
else:
form = ModelFormGenericItem(request.POST)
form = ModelFormGenericItem(request.POST)
if form.is_valid():
#process the data in form.cleaned_data
instance = form.save(commit = False)
instance.owner_id = request.user.id
instance.save(safe=True, cascade=)
return HttpResponseRedirect('/thanks/')
else:
# Ensure that this is a "final" category:
p = get_object_or_404( Category, categoryTitle = category )
i = Category.objects.filter( parentCategory = p )
if i.count() != 0:
raise Http404
if category == 'Muffins':
form = ModelFormMuffin()
elif category == 'Cameras':
form = ModelFormCameras()
else:
form = ModelFormGenericItem()
return render(request, 'item.html', {
'form': form,
'category': category,
} )
更多来自 Django 错误:
/Users/holografix/Documents/development/troca_proj/troca_app/views.py in add_item
instance.save() ...
▶ Local vars
/Users/holografix/.virtualenvs/troca/lib/python2.7/site-packages/mongoengine/document.py in save
warn_cascade = not cascade and 'cascade' not in self._meta ...
▶ Local vars
/Users/holografix/.virtualenvs/troca/lib/python2.7/site-packages/mongodbforms/documentoptions.py in __getitem__
return self.meta[key] ...
▶ Local vars