The path problem of django media file

problem description

version note: python3.6.5 django 2.0.8 django restframework 3.8
WeChat Mini Programs development, using django as the backend. In the program for processing photos, when the picture is uploaded through the ImageField field, the picture url returned through django restframework begins with http instead of https (the site uses the https protocol)

Field Settings :

image = models.ImageField(upload_to="themes/%Y/%m/%d", null=True, blank=True)

media related settings :

MEDIA_ROOT = os.path.join(BASE_DIR, "media/")
MEDIA_URL = "/w3/media/"

the expected image field value for a model instance

"https://img.codeshelper.com/upload/img/2021/10/12/jxukjw4t4cc105.jpg"

actual return value:

"http://mysite.com/w3/media/themes/2018/11/01/example.jpg"
Oct.12,2021

customize ImageField and re-implement the to_representation method.

from django.conf import settings
from rest_framework import serializers

domain = 'mysite.com'

class HttpsImageField(serializers.ImageField):
    def to_representation(self, value):
        return 'https://{}{}{}'.format(domain, settings.MEDIA_URL, str(value))
        
class MySerializer(serializers.ModelSerializer):
    ...
    image = HttpsImageField(use_url=False)
    ...
Menu