taghiss
taghiss

Reputation: 115

DRF testing Model Serializer - Django Restframework

I am testing my Serializer model in django restframework with APITestCase. this is my structure :

class Usertest(APITestCase):
    def test_userprofile_create(self):
        user = User.objects.create(username='asghar', 
                                   password='4411652A', 
                                   email='[email protected]',)
        profile = UserProfile.objects.create(fullname='asghariiiiii', 
                                             phonenumber='9121345432',
                                             address='bella', 
                                             user=user)
        user.user_profile = profile
        client = APIClient()
        request = client.get('/user/create/')
        data = UserCreateSerializer(user, 
                                    context={'request': request}).data

        url = reverse('user-create')
        response_create =client.post(url, data)

in my view permissions set to AllowAny. no need for login or force_authenticate.

data = UserCreateSerializer(user, context={'request': request}).data AttributeError: 'HttpResponseNotFound' object has no attribute 'build_absolute_uri'

as you can see error comes from creating data .first i tried to remove context but error comes with this title :

AssertionError: HyperlinkedIdentityField requires the request in the serializer context. Add context={'request': request} when instantiating the serializer.

Upvotes: 2

Views: 2185

Answers (2)

Mtzw
Mtzw

Reputation: 48

REST_FRAMEWORK Request doesn't have method build_absolute_uri

return request.build_absolute_uri(url)
AttributeError: 'function' object has no attribute 'build_absolute_uri'

DRF Request and Django HTTP Request isnt the same.

Upvotes: 0

Linovia
Linovia

Reputation: 21006

request = client.get('/user/create/')

This returns a response, not a request. You should be able to work this around by using APIRequestFactory:

from rest_framework.test import APIRequestFactory

# Using the standard RequestFactory API to create a form POST request
factory = APIRequestFactory()
request = factory.post('/user/create/', {})
data = UserCreateSerializer(user, 
                                context={'request': request}).data

Upvotes: 2

Related Questions