发送请求到Django Rest框架

时间:2018-07-27 01:14:10

标签: python django django-rest-framework fetch-api

我正在尝试通过使用api到Django rest框架发送带有文件的发布请求。

urls.py

from django.conf.urls import url
from . import views

urlpatterns = [
    url(r'^lead/$', views.LeadListCreate.as_view()),
    url(r'^test/$', views.test, name='test')
]

views.py

从rest_framework导入泛型     从rest_framework.decorators导入api_view     来自rest_framework.response导入响应

from api.models import Lead
from api.serializers import LeadSerializer, FileUploadFuelSerializer


class LeadListCreate(generics.ListCreateAPIView):
    queryset = Lead.objects.all()
    serializer_class = LeadSerializer


@api_view(['POST'])
def test(request):
    print(request.data)
    print(type(request.data['file']))
    serializer = FileUploadFuelSerializer(data=request.data)
    if serializer.is_valid():
        # serializer.save()
        print('ok')
        return Response({'res': 'Everything's ok'})
    print(serializer.errors)
    return Response({'res': 'none'})

serializers.py

from rest_framework import serializers
from api.models import Lead, FileUploadFuel


class LeadSerializer(serializers.ModelSerializer):
    class Meta:
        model = Lead
        fields = '__all__'


class FileUploadFuelSerializer(serializers.ModelSerializer):
    class Meta:
        model = FileUploadFuel
        fields = '__all__'

models.py

from django.db import models


class Lead(models.Model):
    name = models.CharField(max_length=100)
    email = models.EmailField()
    message = models.CharField(max_length=300)
    created_at = models.DateTimeField(auto_now_add=True)


class FileUploadFuel(models.Model):
    file = models.FileField(upload_to='fuel/')

我的请求

handleSubmit = (event) => {
    event.preventDefault();
    let body = new FormData()
    body.append("file", this.state.file)
    fetch("/api/test/", {
        body,
        headers: new Headers({
            "Cache-Control": "no-cache",
            "Content-Type": "multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW",
        }),
        method: "POST"
    }).then(res => {
        console.log(res.status)
        return res.json()
    }).then((data) => {
        console.log(data)
    }).catch(err => console.log(err));
}

当我使用邮递员发送请求时,它可以工作。

而request.data ['file']的类型为

<class 'django.core.files.uploadedfile.InMemoryUploadedFile'>

问题:

当我使用提取API发送请求时,它无法正常运行。 request.data ['file']的类型为

<class 'str'>

如何解决该问题以获得InMemoryUploadedFile对象而不是str?

0 个答案:

没有答案