gpt4 book ai didi

python - Django 测试 : AttributeError: 'WSGIRequest' object has no attribute 'user'

转载 作者:行者123 更新时间:2023-11-28 21:17:14 25 4
gpt4 key购买 nike

测试:
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)

我的url文件是

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' object has no attribute 'user'

最佳答案

不要为此使用工厂,那是专门用于在没有中间件的情况下测试 View 的。您需要使用您已经用于登录的客户端。

request = self.client.post(reverse('page1:favourite_post'...))

请注意,您不需要在 setUp 方法中创建客户端,它会自动完成。

关于python - Django 测试 : AttributeError: 'WSGIRequest' object has no attribute 'user' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55878970/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com