0

I upload the files to the server to specific folders, organized by projects. (I forgot to mention that I use Docker)

On DB I save:

id

4

path

/var/local/vvv/project-files/project_2/v_5//r_4_C5R1ud0W8AQwnxa.jpg:large.jpeg

filename

r_4_C5R1ud0W8AQwnxa.jpg:large.jpeg

file_type

jpeg

How can I get the absolute path ?

Something like this:

http://127.0.0.1:8000/media/r_4_C5R1ud0W8AQwnxa.jpg

The only thing I could do is:

http://127.0.0.1:8000/api/vv/download_resource/4

but it doesn't work for what i need.

Please HELP

My Model where are the images:

class Resource(utils.SafeDeleteModel):
    path      = models.CharField(max_length=200, null=True)  # just to define where to save to
    file_name = models.CharField(max_length=100, null=True)
    file_type = models.CharField(max_length=100, null=True)

    added_on  = models.DateTimeField(auto_now_add=True)
    added_by  = models.ForeignKey(User, null=True, blank=True)
    comment   = models.TextField(null=True, blank=True)
  • Possible duplicate of [Django serialize imagefield to get full url](https://stackoverflow.com/questions/35522768/django-serialize-imagefield-to-get-full-url) – drdaeman May 25 '17 at 17:10
  • Uh. It seems that you're using `CharField` to manage media. Is there any reason to do this manually instead of using `FileField` or `ImageField`? With `CharField`s you'll have to (re)implement things (e.g. path conversions) in your own code. Can you switch to e.g. `ImageField`s (that would be the most straightforward and clean approach) or there are barriers preventing you from doing so? – drdaeman May 25 '17 at 17:24

1 Answers1

1

You can use a function to serialize any field in Django RF, example:

class FooSerializer(serializers.ModelSerializer):

    foo_image = serializers.SerializerMethodField('get_image_url')

    class Meta:
        model = Foo
        fields = ('image',)

    def get_thumbnail_url(self, obj):
        return obj.image.url

This probably will end up returning what you want.

  • Just a suggestion: if OP needs an absolute URL, he would need something like this: ``` def get_thumbnail_url(self, obj): url = obj.image.url request = self.context.get("request", None) if request is not None: url = request.build_absolute_uri(url) return url ``` – drdaeman May 25 '17 at 17:08
  • it doesn't return what i want –  May 25 '17 at 17:16
  • Seems like you are not storing enough information to build an url like you want then – Gabriel Ecker May 25 '17 at 17:21