Django REST Framework and FileField absolute url

前端 未结 11 814
不知归路
不知归路 2020-12-13 02:10

I\'ve defined a simple Django app that includes the following model:

class Project(models.Model):
    name = models.CharField(max_length=200)
    thumbnail =         


        
11条回答
  •  南笙
    南笙 (楼主)
    2020-12-13 02:52

    To get the url of a file which uses FileField you can just call the url attribute of the FieldFile (this is the file instance not the field), it use the Storage class to determine the url for this file. It's very straightforward if you are using a external storage like Amazon S3 or if your storage changes.

    The get_thumbnail_url would be like this.

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

    You can also use it in the template this way:

    {{ current_project.thumbnail.url }}
    

提交回复
热议问题