我显然已经忘记了关于django的一些非常基本的东西。这是我的views.py:
def sourcedoc_create(request):
if request.method == 'POST': # If the form has been submitted...
form = SourcedocForm(request.POST, request.FILES) # A form bound to the POST data
if form.is_valid(): # All validation rules pass
handle_uploaded_file(request.FILES['doc'])
form.save()
return HttpResponseRedirect('/index/') # Redirect after POST
else:
form = SourcedocForm() # An unbound form
return render_to_response(
'sourcedoc_create.html',
{'form': form},
RequestContext(request)
这是urls.py的相关部分:
url(r'^$', index),
url(r'^index/', index),
url(r'^sourcedoc/create/', sourcedoc_create),
当我运行应用程序时,我在数据库中创建记录,并且上传的文件成功显示在相关目录中(因此我推断form.save工作正常),但后来我得到了:
KeyError at /sourcedoc/create/
0
Request Method: POST
Request URL: http://www.rosshartshorn.net/worldmaker/sourcedoc/create/
Django Version: 1.4.3
看来我的HttpResponseRedirect无论出于何种原因都无法正常工作,而且它正试图重新发布POST并从空白表单中抛出KeyError?或者其他的东西。无论如何,它不会重定向。当我手动转到/ index /时,一切都很好,新记录就在那里。
我的重定向有什么问题?
如果表格相关:
<body>
{% if form.errors %}
<p style="color: red;">
Please correct the error{{ form.errors|pluralize }} below.
</p>
{% endif %}
<h1>New Post</h1>
<form enctype="multipart/form-data" action="" method="post">
<table>
{{ form.as_table }}
</table>
{% csrf_token %}
<input type="submit" value="Submit">
</form>
另外,我正在使用mongoforms,它应该像ModelForms一样工作:
from mongodbforms import DocumentForm
class SourcedocForm(DocumentForm):
class Meta:
document = Sourcedoc
答案 0 :(得分:0)
这篇帖子似乎至少有点相关:Django MongodbForms KeyError _meta['cascade']。
所以,我刚刚升级到Django 1.5和最新的mongodbforms。这消除了这个错误,虽然我当时遇到了类似这样的问题: MongoKit "ImportError: No module named objectid " error
我刚刚从第二篇文章中实现了keppla的答案,现在它似乎有用了!