Reputation: 3869
I have a model with a FileField and a serializer for this model including the file field. In my viewset, the serializer writes a full URL (one starting with http://) for the file field without me specifying anything. But if I call manually the serializer, the url starts at /media.
Here is a little code :
class ArtworkView(viewsets.ModelViewSet):
"""
View that handle Artwork
"""
queryset = Artwork.objects.all()
serializer_class = ArtworkSerializer
permission_classes = (
permissions.IsAuthenticatedOrReadOnly,
IsArtistOrReadOnly,
)
def list(self, request, *args, **kwargs):
pass
And the test that crashes because of "http://testserver/media/file.jg" != "/media/file.jpg"
def test_list(self):
artworks = Artwork.objects.all()
artworks_serialized = ArtworkSerializer(artworks, many=True)
artwork = self.create_artwork()
request = self.factory.get('/api/v1/artworks/')
view = ArtworkView.as_view({'get': 'list'})
resp = view(request)
self.assertEqual(resp.status_code, 200)
self.assertListEqual(resp.data, artworks_serialized.data) #crashes
Thanks for your help !
Upvotes: 2
Views: 1570
Reputation: 20996
The reason is your serialization is done out of the scope of a request. By default, they'll be passed in the serializer context because they are required for HyperLinked data.
You should create a fake request with the RequestFactory and pass it to the serializer's context:
artworks_serialized = ArtworkSerializer(
artworks, many=True,
context={'request': request})
Upvotes: 4