django rest framework https for absolute urls?

2019-02-25 03:07发布

问题:

The server hosting the api is returning http for absolute urls even though the page was loaded using https, does this have something to do with django rest framework? because there doesn't seem any obvious way to remedy this.

It's the url field in the Meta class that is relevant

class NewsSerializer(serializers.HyperlinkedModelSerializer):
    user = UserSerializer(read_only=True)
    source = serializers.CharField(source='get_source_url', read_only=True)
    comments_count = serializers.IntegerField(read_only=True)
    date_added = serializers.CharField(source='humanize_date_added',
                                       read_only=True)
    is_owner = serializers.SerializerMethodField()
    user_voted = serializers.SerializerMethodField()
    favorited = serializers.SerializerMethodField()
    image = serializers.SerializerMethodField()    

    def create(self, validated_data):
        user = self.context['request'].user
        story = News(user=user, **validated_data)
        story.save()
        return story    

    def get_is_owner(self, obj):
        user = self.context['request'].user
        if user.is_active and user == obj.user:
            return True
        return False    

    def get_user_voted(self, obj):
        user = self.context['request'].user
        if user.is_active:
            return obj.user_voted(user)
        return None    

    def get_favorited(self, obj):
        user = self.context['request'].user
        if user.is_active:
            return obj.is_favorite(user)    


    class Meta:
        model = News
        fields = ('id', 'link', 'title', 'text', 'source', 'user',
                  'date_added', 'image', 'comments_count', 'url',
                  'upvotes', 'downvotes', 'user_voted', 'type',
                  'is_owner', 'favorited')
        read_only_fields = ('date_added')

i am not sure if it has to do with nginx but i have this in the config

proxy_set_header   Host             $host;
proxy_set_header   X-Real-IP        $remote_addr;
proxy_set_header   X-Forwarded-For  $proxy_add_x_forwarded_for;

回答1:

You need to make sure nginx forwards the client's request scheme because it'll make a regular http request to Django. You'll need to add the following line to your vhost definition:

proxy_set_header X-Forwarded-Proto $scheme;


回答2:

Are you using Rest Framework reverse() function to build URLs? http://www.django-rest-framework.org/api-guide/reverse/

It uses incoming request to determine the protocol used.