Why do I get an InvalidDocument exception when saving an object into MongoDB in Django for the first time?

这一生的挚爱 提交于 2019-12-04 18:47:42

I got this error until updating the django-mongodb-engine library to the current version in the 'develop' branch of the github repository. Simply using the instructions on the article shown will import the master branch.

I have also followed this tutorial and had same error. I managed to fix this problem. What I did wrong is I used djangotoolbox from github (https://github.com/django-nonrel/djangotoolbox) repository, which was ver 0.9.2. Then I removed this and did it as tutorial states and used bitbucket (https://bitbucket.org/wkornewald/djangotoolbox) that is on ver 0.9.1 of djangotoolbox. Now it works fine.

Does this work:

post = Post(
...     title='Hello MongoDB!',
...     text='Just wanted to drop a note from Django. Cya!',
...     tags=['mongodb', 'django'],
...     comments=['comment 1', 'comment 2']
... ) 

Another thing to try:

class Post(models.Model):
    title = models.CharField(primary_key=True, max_length=200)

I think by default Django uses auto-generated numeric values as primary keys. This would force your title to be your primary key... it's a char string, so it might solve the problem you're seeing. It's just a guess, because the actual error your seeing doesn't make too much sense to me.

From what I see, your model looks just fine. The error is funny; it is saying that the key to the attribute you are calling as "title" cannot be anything other than a string, but if I'm not mistaken, the string here is the key "title" and the value is the CharField() field, together representing a key/value pair in the Post document in your MongoDB. Try isolating the problem by jumping into the django shell:

python manage.py shell

and building your Post object from scratch. Use the model that dragonx has mentioned. Simple is best to debug these problems. If you are getting the same error when you try either to call Post.objects.create(p) for a Post object p, or when you call p.save(), try re-writing the Post model and give it another shot.

Finally, you can show us your settings.py file and see what your mongodb settings are there. If you say you are using django-nonrel, then there are basic checks you can make to ensure that python, django, and mongodb are talking to each other.

Let us know how you're doing.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!