How to output the port after the IP address in a resource URL in Django?

后端 未结 1 1630
盖世英雄少女心
盖世英雄少女心 2020-12-18 06:52
  1. How do I add the host port to the URLs in my serialized responses? Django is currently providing them without port so the links are broken.
  2. Or, if adding the
相关标签:
1条回答
  • 2020-12-18 07:35

    I finally found out how to fix the image URLs thanks to this question which is slightly different.

    Solution 1

    Add the port number in the Host header in the nginx config as follows:

        location / {
            proxy_pass http://hello_django;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_set_header Host $host:1337;                               <<------- HERE
            proxy_redirect off;
        }
    

    Solution 2

    Change the Host header in the nginx config to http_host as follows:

        location / {
            proxy_pass http://hello_django;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_set_header Host $http_host;                               <<------- HERE
            proxy_redirect off;
        }
    

    In either case, the image URLs are now returned as follows by DRF (image link).

    HTTP 200 OK
    Allow: GET, HEAD, OPTIONS
    Content-Type: application/json
    Vary: Accept
    
    {
        "count": 1,
        "next": null,
        "previous": null,
        "results": [
            {
                "id": 2,
                "user": 1,
                "title": "First post",
                "slug": "first",
                "image_url": "http://0.0.0.0:1337/mediafiles/publisher/background.gif",    <----HERE
                "content": "Second post content.",
                "draft": false,
                "publish": "2019-05-22",
                "updated": "2019-05-22T09:41:36.257605Z",
                "timestamp": "2019-05-22T07:58:01.471534Z"
            }
        ]
    }
    
    0 讨论(0)
提交回复
热议问题