尝试使用Django MongoDBForms替换ModelForms但是在保存表单实例时我得到了这个非常奇怪的错误。
在save()期间,mongoengine.Document检查MongoDBForm包装的_meta dict中的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
答案 0 :(得分:0)
编辑: 为documentoptions.py实现包含()方法似乎无需更改任何其他内容即可修复它。
结束了对这个问题的黑客攻击,因为我不知道它为什么会发生......
为mongodbforms.documentoptions添加了“has_key()”方法:
def has_key(self, key):
return self.meta.has_key(key)
并将mongoengine中的违规行从 in 运算符更改为检查has_key()方法:
warn_cascade = not cascade and not self._meta.has_key('cascade')
如果有人能够只回答WTF,那么原始错误就会突然出现,那真是太棒了!