I.Z.
I.Z.

Reputation: 197

Django REST Framework. How to get full url of a page with protocol, domain, and path?

There is Django REST framework. I need to unload the full path of the page into the tag. For example, there is a page:

https://domain-name.com/category/article

In serializers.py:

class someClass(serializers.ModelSerializer):
    url = serializers.URLField(source='get_absolute_url', read_only=True)
    class Meta:
        model = onlyURL
        fields = ['url']

This does not work correctly, since I do not get the full url, only part:

<url>**/category/article**</url>

How to get full url with protocol, domain, and path?

Upvotes: 1

Views: 2397

Answers (1)

ruddra
ruddra

Reputation: 52028

You can use serializers.SerializerMethodField() for this. For example:

class SomeClass(serializers.ModelSerializer):
    url = serializers.SerializerMethodField()
    class Meta:
        model = OnlyURL # using CamelCase for declaring Model Class
        fields = ['url']

    def get_url(obj):
       request = self.context.get('request')
       abs_url = obj.get_absolute_url()
       return request.build_absolute_uri(abs_url)

Also make sure to pass request as extra argument or use Generic Views/Viewsets for this implementation.

Upvotes: 3

Related Questions