我正在测试本教程中的django应用程序:http://tutorial.djangogirls.org/en/django_admin/README.html
我已经创建了一个测试:
from django.test import TestCase
from django.utils import timezone
from .models import Post
from django.contrib.auth.models import User
# Create your tests here.
class PostTest(TestCase):
def test_create_post(self):
# Create the post
post = Post()
# Set the attributes
post.author = User
post.title = 'My first post'
post.text = 'This is my first blog post'
post.published_date = timezone.now()
post.created_date = timezone.now()
# Save it
post.save()
# Check we can find it
all_posts = Post.objects.all()
self.assertEquals(len(all_posts), 1)
only_post = all_posts[0]
self.assertEquals(only_post, post)
# Check attributes
self.assertEquals(only_post.author, User)
self.assertEquals(only_post.title, 'My first post')
self.assertEquals(only_post.text, 'This is my first blog post')
self.assertEquals(only_post.published_date.day, post.published_date.day)
self.assertEquals(only_post.published_date.month, post.published_date.month)
self.assertEquals(only_post.published_date.year, post.published_date.year)
self.assertEquals(only_post.published_date.hour, post.published_date.hour)
self.assertEquals(only_post.published_date.minute, post.published_date.minute)
self.assertEquals(only_post.published_date.second, post.published_date.second)
self.assertEquals(only_post.created_date.day, post.created_date.day)
self.assertEquals(only_post.created_date.month, post.created_date.month)
self.assertEquals(only_post.created_date.year, post.created_date.year)
self.assertEquals(only_post.created_date.hour, post.created_date.hour)
self.assertEquals(only_post.created_date.minute, post.created_date.minute)
self.assertEquals(only_post.created_date.second, post.created_date.second)
当我运行python manage.py test
时,我收到此错误:
Creating test database for alias 'default'...
ERROR: test_create_post (blog.tests.PostTest)
Traceback (most recent call last):
File "C:\Users\shenk\Documents\Programming\django_projects\djangogirls\blog\tests.py" , line 13, in test_create_post
post.author = User
File "c:\Users\shenk\Documents\Programming\django_projects\djangogirls\myvenv\lib\site-packages\django\db\models\fields\related.py", line 627, in __set__
self.field.rel.to._meta.object_name,
ValueError: Cannot assign "<class 'django.contrib.auth.models.User'>": "Post.author" must be a "User" instance.
----------------------------------------------------------------------
Ran 1 test in 0.001s
如何创建User实例的对象来测试Post?在我的模型中,它被定义为author = models.ForeignKey('auth.User')
答案 0 :(得分:3)
这条线看起来很虚伪:
# Set the attributes
post.author = User
post.author希望您为其分配User类的实例,而不是User类本身。尝试类似:
u = User(...)
u.save()
post.author = u