测试:
1)用用户登录
2)最喜欢的帖子
class FormTest(TestCase):
def setUp(self):
self.user = ProjectUser.objects.create(username='testUser',
email='testUser@user.com')
self.user.set_password('testPassword')
self.user.save()
self.client = Client()
self.factory = RequestFactory()
def sometest(self):
self.client.login(username='testUser', password='testPassword')
user = auth.get_user(self.client)
assert user.is_authenticated
new_object_2 = SampleModel.objects.create(unique_id='123456', name='sample')
request = self.factory.post(reverse('page1:favourite_post', kwargs={'fav_id': new_object_2.id}))
response = favourite_post(request, new_object_2.id)
print(response)
我的网址文件是
path('favourite_post/<int:fav_id>', views.favourite_post, name='favourite_post'),
views.py是
def favourite_post(request, fav_id):
post = get_object_or_404(Post, id=fav_id)
if request.method == 'POST':
if post.favourite.filter(id=request.user.id).exists():
post.favourite.remove(request.user)
else:
post.favourite.add(request.user)
return HttpResponseRedirect(reverse('page:some_page', args=(fav_id,)))
我得到的错误是
AttributeError:'WSGIRequest'对象没有属性'user'
答案 0 :(得分:1)
不要为此使用工厂,这是专门用于在没有中间件的情况下测试视图的方法。您需要使用已经用于登录的客户端。
request = self.client.post(reverse('page1:favourite_post'...))
请注意,您不需要通过setUp方法创建客户端,而是自动完成的。