samedi 27 avril 2019

Django testt: AttributeError: 'WSGIRequest' object has no attribute 'user'

The test:
1) login with a user
2) favourite a post

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)

My url file is

path('favourite_post/<int:fav_id>', views.favourite_post, name='favourite_post'),

The views.py is

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,)))

The error I get is

AttributeError: 'WSGIRequest' object has no attribute 'user'

Aucun commentaire:

Enregistrer un commentaire