Pls How can I save the full url of an uploaded file from cloudinary in my postgres database?

Options
Kevin
Kevin Member Posts: 4
edited September 2023 in Developer APIs

Anytime I upload a file, in my api, i get the full url of the uploaded file from cloudinary, eg : https://res.cloudinary.com/dug5dj4uz/image/upload/nun_p9jduh".

But in my database, the image is stored as " image/upload/v1694654259/nun_p9jduhf.jpg "

i want to be able to save the full url of the uploaded file from cloudinary in my database



This is my code


models.py

class Posts(models.Model):

    id = models.UUIDField(default=uuid.uuid4, primary_key=True, editable=False)

    user = models.ForeignKey(User, on_delete=models.CASCADE)

    files = CloudinaryField(resource_type='auto', folder='Insagram_Posts', default='')

    description = models.TextField(blank=True)

    created = models.DateTimeField(default=timezone.now)


serializers.py

class PostsSerializer(serializers.ModelSerializer):

    class Meta:

        model = Posts

        fields = ['id', 'files', 'description']


    def to_representation(self, instance):

        representation = super().to_representation(instance)

        representation['files'] = f'https://res.cloudinary.com/dug5dj4uz/{representation["files"]}'

        return representation

   


views.py

class PostListCreateView(generics.ListCreateAPIView):

    permission_classes = (IsAuthorOrReadOnly, )

    authentication_classes = (TokenAuthentication, )

    queryset = Posts.objects.all()

    serializer_class = ReadPostsSerializer



    def post(self, request, format=None, *args, **kwargs):

        serializer = PostsSerializer(data=request.data)

       

        # if the new serialized post is valid, then save

        if serializer.is_valid():

            # This line checks if the user is authorized to make a post

            serializer.validated_data['user'] = request.user

            post = serializer.save()


            # Getting the auther of the post

            user_serializer = UserSerializer(request.user)



            post.save()

            data = {

                'user': user_serializer.data,

                'id': post.id,

                'description': post.description,

                'files': post.files,

            }

            return Response(data, status=status.HTTP_201_CREATED)

        else:

            return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

Tagged:

Answers

  • DannyFromCloudinary
    DannyFromCloudinary Member, Cloudinary Staff Posts: 101
    Options

    Hey @Kevin. Thanks for getting in touch with your question. I'm not a Python expert, so I shall answer in a broader context:

    When saving information about an asset in your database, it's a good practice to save the different parameters you require, and then build out the URL upon delivery, rather than just saving a delivery URL. A delivery URL is made up of https://res.cloudinary.com/cloud_name/asset_type/delivery_type/transformations/version/public_id.extension . Your cloud name will remain constant, but the other parameters will vary, and should be saved into your database for later retrieval. The easiest way to do this would be to read the parameters from the upload response (example available here) and save the relevant fields into your DB.

    If you're trying to import data into your database for assets already on your account, you can use the Admin API to list all assets in your account. and then parse the response into your database.

    I hope this helps, but feel free to raise a support ticket if you need any further assistance.

    Kind regards,

    -Danny