从Serializer调用另一个序列化程序会弄乱URI

时间:2017-12-28 10:04:53

标签: django django-rest-framework django-settings

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

这是当前的JSON数据

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

以下是AWS设置的工作示例。它正确显示http://localhost:8000/media/blahblah

    # 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

仅当我在序列化程序中调用另一个 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.

1 个答案:

答案 0 :(得分:2)

您可以使用请求的build_absolute_uri方法:

/

请注意,您可能需要在视图中向序列化程序的上下文添加请求:

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)

但是如果您使用基于通用类的视图,这将自动执行。