从序列化程序中调用另一个序列化程序会弄乱URI [英] Calling another serializer from the Serializer messes up URI

查看:79
本文介绍了从序列化程序中调用另一个序列化程序会弄乱URI的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我处于调试模式,我想设置默认的ImageField以返回完整的URL localhost:8000/path .

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

这是当前的JSON数据

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

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

这里是使用AWS设置的有效示例.它会正确显示 http://localhost:8000/media/blahblah .

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

仅当我在序列化程序中调用另一个序列化器时,这种情况发生

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.

推荐答案

您可以使用请求的

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.

这篇关于从序列化程序中调用另一个序列化程序会弄乱URI的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆