DB在Django中不断爆炸

时间:2017-08-21 13:59:06

标签: python django sqlite django-models

我正在尝试使用django,到目前为止,除了重复的数据库问题之外,我发现它是惊人的。

我最近关注的是Django by Example一书,我已经按照所有内容进行了操作,但是当按照一些简单的指令通过python shell api添加一些数据时,我得到以下内容:

>>> from django.contrib.auth.models import User
>>> from blog.models import Post
>>> user = User.objects.get(username='jamie')
>>> Post.objects.create(title='One More Post', slug='one-more-post', body='Post body', author='user')
Traceback (most recent call last):
  File "/Users/jamie/dev/venv/lib/python3.6/site-packages/django/core/management/commands/shell.py", line 69, in handle
self.run_shell(shell=options['interface'])
  File "/Users/jamie/dev/venv/lib/python3.6/site-packages/django/core/management/commands/shell.py", line 61, in run_shell
raise ImportError
ImportError

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "<console>", line 1, in <module>
  File "/Users/jamie/dev/venv/lib/python3.6/site-packages/django/db/models/manager.py", line 127, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
  File "/Users/jamie/dev/venv/lib/python3.6/site-packages/django/db/models/query.py", line 346, in create
obj = self.model(**kwargs)
  File "/Users/jamie/dev/venv/lib/python3.6/site-packages/django/db/models/base.py", line 468, in __init__
setattr(self, field.name, rel_obj)
  File "/Users/jamie/dev/venv/lib/python3.6/site-packages/django/db/models/fields/related.py", line 629, in __set__
self.field.rel.to._meta.object_name,
ValueError: Cannot assign "'user'": "Post.author" must be a "User" instance.

这是在遵循多个教程时发生的,我很难过。我遵循标准说明并通过终端安装,pip,python和django。还使用虚拟环境,所以不确定为什么会发生这种情况。

1 个答案:

答案 0 :(得分:1)

使用此代替您的陈述。

使用user变量代替'user'字符串。

Post.objects.create(title='One More Post', slug='one-more-post',
                    body='Post body', author=user)