从rest_framework检索Django中的图像

时间:2019-11-27 13:27:46

标签: python django django-rest-framework

models.py:

from __future__ import unicode_literals
from django.db import models
class Photo(models.Model):
    title = models.CharField(max_length=255, blank=True)
    file = models.FileField()
    uploaded_at = models.DateTimeField(auto_now_add=True)

serializers.py:

from rest_framework import serializers
from . models import Photo

class imageSerializer(serializers.ModelSerializer):
    class Meta:
        model = Photo
        fields='__all__'

views.py:

from django.shortcuts import render,redirect
from django.http import JsonResponse
from django.views import View
import time
from rest_framework import generics
from .forms import PhotoForm
from .models import Photo
from django.http import HttpResponse
from rest_framework.response import Response
from django.shortcuts import get_object_or_404
from rest_framework.views import APIView
from rest_framework import status
from .serializers import imageSerializer 
import requests       


class DragAndDropUploadView(View):
    def get(self, request):
        photos_list = Photo.objects.all()
        return render(self.request, 'UploadMulti/drag_and_drop_upload/index.html', {'photos': photos_list})

    def post(self, request):
        form = PhotoForm(self.request.POST, self.request.FILES)
        if form.is_valid():
            photo = form.save()
            data = {'is_valid': True, 'name': photo.file.name, 'url': photo.file.url}
        else:
            data = {'is_valid': False}
        return JsonResponse(data)


def clear_database(request):
    for photo in Photo.objects.all():
        photo.file.delete()
        photo.delete()
    return redirect(request.POST.get('next'))



class ImagesList(APIView):
    def get(self,request):
        imagelist=Photo.objects.all()
        serializer = imageSerializer(imagelist,many=True)
        return Response(serializer.data) 
    def post(self):
        pass    

def backend(request):
    response = requests.get('http://localhost:8000/images/')
    api_values = response.json()
    for values in api_values:
        print(type(values['file']))
    return render(request,"home.html",{'data':api_values})

当我打印values.file的类型时,这是我获取的图像数据,因此在将其发送到前端时不显示图像

如何从rest api检索为图像文件?

HTTP 200 OK
Allow: GET, POST, HEAD, OPTIONS
Content-Type: application/json
Vary: Accept

[
    {
        "id": 1,
        "title": "",
        "file": "think-twice-code-once.jpg",
        "uploaded_at": "2019-11-27T12:34:32.270786Z"
    }
]

是否还有其他方法可以从rest框架获取图像以及图像是否以图像格式存储?

1 个答案:

答案 0 :(得分:0)

问题是由于您为此特定序列化程序配置了FileField而引起的。您需要use_url为True。因此,您可以更改UPLOADED_FILES_USE_URL设置或在use_url=True中设置imageSerializer,如下所示。

class imageSerializer(serializers.ModelSerializer):
    class Meta:
        model = Photo
        fields='__all__'
    file = serializers.FileField(use_url=True)

旁注,imageSerializer应该确实是ImageSerializer,以遵守python类的命名准则。