Home > Blockchain >  full link for media in django-rest
full link for media in django-rest

Time:11-24

I wrote this view:

api_view(["GET"])
def article_grid_list(request):
    # fetched data from database
    data = Articles.objects.all().order_by("-created_date")[:11]
    pinned_article = Articles.objects.get(pinned=True)

    # serialized data
    pinned_data = ArticlesSerializer(pinned_article)
    horizontal_data = ArticlesSerializer(data[:3], many=True)
    small_data = ArticlesSerializer(data[3:8], many=True)
    card_data = ArticlesSerializer(data[8:], many=True)

    final_data = {
        "pinned":pinned_data.data,
        "horizontal": horizontal_data.data,
        "small": small_data.data,
        "card": card_data.data
    }

when I print result of this route, I'm getting 'cover' field like this : "cover": "/media/article/artice_cover_NkOUuZ7vH3zEejCgV.jpg",

but when I write this function like ModelViewSet I'm getting full url of cover field and I want to get full URL in every request

modelViewSet example :

class ArticleGridList(viewsets.ModelViewSet):
    queryset = Articles.objects.all().order_by("-created_date")
    serializer_class = ArticlesSerializer

I expect this: "cover": "http://localhost:8000/media/article/artice_cover_NkOUuZ7vH3zEejCgV.jpg"

my app urls.py file :

router = routers.SimpleRouter()
router.register('articles', ArticlesViewSet)
urlpatterns = [
  path("article-grid-list/", article_grid_list)
]   static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

urlpatterns  = router.urls

CodePudding user response:

You need to send context = {'request':request} in serializer like this ...

Way - 1

# serialized data
pinned_data = ArticlesSerializer(pinned_article,context = {'request':request})
horizontal_data = ArticlesSerializer(data[:3], many=True,context = {'request':request})
small_data = ArticlesSerializer(data[3:8], many=True,context = {'request':request})
card_data = ArticlesSerializer(data[8:], many=True,context = {'request':request})

way - 2 (for applying this method you need to add context = {'request':request}` in serializer like the above method.

class ArticleSerializer(serializers.ModelSerializer):
    cover = serializers.SerializerMethodField()
    def get_cover(self,obj):
        request = self.context.get('request')
        return str(request.build_absolute_uri(obj.cover.url))
  • Related