【问题标题】:How to get relative url of ImageField when using ModelViewSet in django rest framework?在django rest框架中使用ModelViewSet时如何获取ImageField的相对url?
【发布时间】:2020-03-24 04:26:34
【问题描述】:

在 Django 休息框架中使用 ModelViewSet 时,我得到了一个 ImageField 的绝对 URL。当我使用开发服务器时,它返回http://localhost:8000/media/abc.png,这对我来说很好。但是当我使用 nginx 服务器时,它返回的 http://localhost/media/abc.png 是不正确的。如您所见,图像路径中缺少端口。我将如何返回具有该 ImageField 的 Nginx 服务器端口的相对 URL 或绝对 URL?

/models.py

class BlogPost(models.Model):
    title_image = models.ImageField(upload_to='blog/title_images/%Y/%m/%d', blank=True, null=True)

/serializers.py

class BlogListSerializer(serializers.ModelSerializer):
    class Meta:
        model = BlogPost
        exclude = ('id',)

/views.py

class BlogViewSet(ModelViewSet):
    parser_classes = (FormParser, JSONParser, MultiPartParser, )
    permission_classes = (AllowAny, )
    authentication_classes = (CsrfExemptSessionAuthentication, BasicAuthentication, )
    queryset = BlogPost.objects.all()
    serializer_class = BlogListSerializer

【问题讨论】:

    标签: python django nginx django-rest-framework django-rest-viewsets


    【解决方案1】:

    你可以这样做。对于 .env 你安装 python-decouple 包。

    class BlogListSerializer(serializers.ModelSerializer):
    
        # Use serializer methodfield to get correct image path
        avatar = serializers.SerializerMethodField()
    
        def get_avatar(self, data):
            return env('MEDIA_URL') + data['title_image']
    
       class Meta:
           model = BlogPost
           exclude = ('id','avatar')
    

    【讨论】:

      猜你喜欢
      • 2013-12-16
      • 2016-08-10
      • 2015-04-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-10-16
      • 2017-11-06
      • 2018-07-06
      相关资源
      最近更新 更多