我在 Django 中编写博客应用程序时遇到了麻烦。
首先,我的models.py:
class Blog(models.Model):
user = models.ForeignKey(User)
blog_title = models.TextField()
def __unicode__(self):
return self.blog_title
class PostManager(models.Manager):
def create_post(self, blog):
post = self.create(blog=blog)
return post
class Post(models.Model):
blog = models.ForeignKey(Blog)
post_title = models.TextField()
post_content = models.TextField()
objects = PostManager()
def __unicode__(self):
return self.post_title
然后是 views.py 文件中导致错误的行:
user = request.user
blog = Blog.objects.get_or_create(
user=user
)
post = Post.objects.create_post(blog)
此行导致错误:
Cannot assign "(<Blog: title1>, False)": "Post.blog" must be a "Blog" instance.
Request Method: POST
Request URL: http://localhost:7777/save/
Django Version: 1.5.1
Exception Type: ValueError
Exception Value:
Cannot assign "(<Blog: title1>, False)": "Post.blog" must be a "Blog" instance.
Exception Location: /Library/Python/2.7/site-packages/django/db/models/fields/related.py in __set__, line 405
Python Executable: /usr/bin/python
Python Version: 2.7.2
Python Path:
['/Users/yoongeemin/Documents/Django/project_blog',
'/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python27.zip',
'/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7',
'/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-darwin',
'/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-mac',
'/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-mac/lib-scriptpackages',
'/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python',
'/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-tk',
'/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-old',
'/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-dynload',
'/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/PyObjC',
'/Library/Python/2.7/site-packages']
我已经尝试解决这个问题几个小时,但我不知道错误意味着什么以及导致问题的原因。任何建议:(??谢谢!