Uploading and Retrieving Images to MongoDB Atlas using Django Rest (HELP)

Viewed 296

I'm having trouble uploading images to Mongo and retrieving them using Django Rest. I am using GridFS and I'm simply trying to upload a profile picture of a user.This what my api looks like after uploading my image

It does not show me a viable link to access it. It just points me back to the create view for some reason. I checked my Mongo Atlas page and it seems like the images are being stored. How can I properly retrieve my images?

Here is the code I wrote:

settings.py
BASE_URL = 'http://127.0.0.1:8000/'

models.py

grid_fs_storage = GridFSStorage(collection='myfiles', base_url=''.join([settings.BASE_URL, 'myfiles/']))
class ProfilePic(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    profile_pic = models.ImageField(upload_to='users',
        default='avatar.png',storage=grid_fs_storage)



serializers.py
class ProfilePicSerializer(serializers.ModelSerializer):
    class Meta:
        model = models.ProfilePic
        fields = ('id', 'profile_pic')



views.py

class ProfilePicView(viewsets.ModelViewSet):
    authentication_classes = (authentication.TokenAuthentication,)
    permission_classes = (permissions.IsAuthenticated,)
    queryset = models.ProfilePic.objects.all()
    serializer_class = ProfilePicSerializer
1 Answers

maybe you should try something like this:

class ProfilePic(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    profile_pic = models.ImageField(upload_to='users',
        default='avatar.png',storage=grid_fs_storage)

    def get_picture(self, obj):
        return obj.profile_pic.url
Related