2017-08-21 47 views
0

我正在嘗試使用Django,到目前爲止,我發現除了重複的數據庫問題之外,它是驚人的。DB在Django中不斷爆炸

我最近以例本書以下的Django和我都遵循一切爲信,但以下一些簡單的指令,當通過蟒蛇Shell編程,我得到以下補充一些數據:

>>> 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。也使用虛擬env,所以不知道爲什麼會發生這種情況。

+0

您的文章模型預計的用戶實例(要傳遞的文本字符串,而不是用戶實例變量「用戶」) –

+0

哦,那是令人尷尬的:)我固定的,但我仍然得到回溯錯誤的線69和線61. – user8467470

+0

非常感謝您的幫助 - 我剛剛檢查了本書的勘誤表,並且未發佈var post =。 – user8467470

回答

1

使用此代替您的語句。

使用user變量而不是'user'字符串。

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

謝謝。痛苦的新手錯誤:) – user8467470