Not able to GET Image from Django Rest API

2019-07-08 05:45发布

问题:

I'm learning Django Rest Framework & facing some issue.

I have a small Task App API.

I'm able to save an image on the server but not able to get Image from API image hyperlink.

My Model.py

class Task(models.Model):
    task_name = models.CharField(max_length=30)
    task_desc = models.CharField(max_length=30)
    image = models.ImageField(upload_to = 'pic_folder/', default = 'pic_folder/None/no-img.jpg')

Views.py

class TaskViewSet(viewsets.ModelViewSet):
    queryset = Task.objects.all()
    serializer_class = TaskSerializer

serializer.py

class TaskSerializer(serializers.HyperlinkedModelSerializer):
    image = serializers.ImageField(
            max_length = None, use_url=True
        )   
    class Meta:
        model = Task
        fields = ('id','task_name','image')

settings.py

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

APP Structure:-

TaskAPI  (Base Dir)
    TaskAPP
     media

I can Make a Request For POST successfully & It show correct image link but when i click on image link it gives error.

Error:- Please suggest how to get Image from link.

回答1:

You did not included the media url in your urls.py

from django.conf.urls.static import static
from django.conf import settings

urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

see the docs on serving media and static files.