1

I am getting an absolute URL of an ImageField when using ModelViewSet in the Django rest framework. When I am using a development server, its returning http://localhost:8000/media/abc.png and this is fine for me. But when I am using the nginx server, its returning http://localhost/media/abc.png which is incorrect. As you can see that the port is missing in the imagepath. How would I return the relative url or absolute URL with the port for the Nginx server for that ImageField?

/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
Rajesh Samui
  • 167
  • 1
  • 2
  • 12

1 Answers1

1

You can do like this. for .env you install python-decouple package.

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')