Search code examples
djangodjango-rest-frameworkdjango-settings

Calling another serializer from the Serializer messes up URI


I'm in the debugging mode and I want to set default ImageField to return full URLlocalhost:8000/path.

Here is current JSON data

 ...
 "img": "http://localhost:8000/media/outfits/1/4.png",
    "tagged_clothes": [
        {
            "cloth_image": "/media/clothes/1/7.png", <- This happens when I use settings.py debugging file
            "id": 6,
            "b_clothtype": "ETC",

settings.py

MEDIA_URL = '/media/' # if I change this variable as 'localhost:8000/media/',
                      # JSON returns correct URLs but I couldn't see the image.
MEDIA_ROOT = os.path.join(os.path.dirname(BASE_DIR), 'media_cdn') 

Here is working example with AWS settings. It shows http://localhost:8000/media/blahblah correctly.

    # HERE is working example in AWS. It returns full URI
# AWS_ACCESS_KEY_ID = "aws key" #S3
# AWS_SECRET_ACCESS_KEY = "secret key" #S3
# AWS_FILE_EXPIRE = 200 #S3
# AWS_PRELOAD_METADATA = True #S3
# AWS_QUERYSTRING_AUTH = True #S3
# DEFAULT_FILE_STORAGE = 'asd' #S3
# STATICFILES_STORAGE = 'asd' #S3
# AWS_STORAGE_BUCKET_NAME = 'asd' #S3
# S3DIRECT_REGION = 'us-west-2' #S3

# S3_URL = '//%s.s3.amazonaws.com/' % AWS_STORAGE_BUCKET_NAME #S3
# MEDIA_URL = '//%s.s3.amazonaws.com/media/' % AWS_STORAGE_BUCKET_NAME #S3
# MEDIA_ROOT = MEDIA_URL #S3

# STATIC_URL = S3_URL + 'static/' #S3
# import datetime #S3
# two_months = datetime.timedelta(days=61) # S3
# date_two_months_later = datetime.date.today() + two_months #S3
# expires = date_two_months_later.strftime("%A, %d %B %Y 20:00:00 GMT") #S3
# AWS_HEADERS = { #S3
#   'Expires': expires,
#   'Cache-Control': 'max-age=%d' % (int(two_months.total_seconds()), ),
# }

urls.py

if settings.DEBUG:
    urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
    urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

CODE

This happens only if I call another Serializer in the serializer

def get_tagged_clothes(self, obj):
        clothes = obj.clothes_set;
        if obj.user != self.context['request'].user:
            clothes = clothes.filter(only_me=False)
        return CListSerializer(clothes, many=True).data <- Sending wrong URI.

Solution

  • You can use request's build_absolute_uri method:

    class ClothesListSerializer(serializers.ModelSerializer):
        cloth_image = serializers.SerializerMethodField()
    
        class Meta:
            model = Cloth
            fields = ('cloth_image' ...)
    
    
        def get_cloth_image(self, obj):
            request = self.context.get('request')
            photo_url = obj.cloth_image.url
            return request.build_absolute_uri(photo_url)
    

    Note that you may need to add request to serializer's context inside your view for this:

    serializer = ClothesListSerializer(Cloth, context={'request': request})
    

    But if you are using generic class based view this will do automatically.