gpt4 book ai didi

django - 使用 Django Rest Framework 上传文件时出现错误 "No file was submitted."

转载 作者:行者123 更新时间:2023-12-02 00:57:14 33 4
gpt4 key购买 nike

在尝试使用带有 Content-Type 的 Postman 上传文件时 - 标题中的 multipart/form-data。我正在传递这两个字段,但出现以下错误:

Error:{"upload_to": ["This field is required."],"file_object": ["No file was submitted."]}



网址.py
from django.conf.urls import include, url
from rest_framework_nested import routers
from utils.views import TemporaryImageView
from . import views

router = routers.SimpleRouter(trailing_slash=False)

urlpatterns = [
url(r'^', include(router.urls)),
url(r'^upload-temp-image/$', TemporaryImageView.as_view())
]

View .py
from rest_framework import viewsets, filters
import django_filters.rest_framework
from rest_framework.generics import CreateAPIView
from rest_framework.parsers import FileUploadParser, MultiPartParser, FormParser
from utils.serializers.temporary_image import TemporaryImageSerializer

class TemporaryImageView(CreateAPIView):
parser_classes = (MultiPartParser,)
serializer_class = TemporaryImageSerializer

序列化程序.py
from rest_framework import serializers
from utils.models.tempfile import TemporaryFile

class TemporaryImageSerializer(serializers.ModelSerializer):
choices = (('Company Logo','/company/logos/'),
)
upload_to = serializers.ChoiceField(choices=choices)
file_object = serializers.ImageField()

class Meta:
model = TemporaryFile
fields = ('upload_to', 'file_object')

模型.py
from django.db import models
class TemporaryFile(models.Model):
"""
a temporary file to backend
"""

file_object = models.FileField(blank=False, null=False)
timestamp = models.DateTimeField(auto_now_add=True)

def __unicode__(self):
return str(self.id)

请帮助...我不知道出了什么问题。

最佳答案

我已经按照下面的方式更改了我的 models.py 文件,它按预期工作..
模型.py

from django.db import models

def get_image_path(instance, filename):

if instance.upload_to == "company_logo":
path = 'company/logo/'
return path


class TemporaryFile(models.Model):
"""
a temporary file to backend
"""

file_object = models.FileField(blank=False, null=False, upload_to=get_image_path)
timestamp = models.DateTimeField(auto_now_add=True)

def __unicode__(self):
return str(self.id)

def __init__(self, *args, **kwargs):
self.upload_to = kwargs.pop("upload_to")
super(TemporaryFile, self).__init__(*args, **kwargs)

关于django - 使用 Django Rest Framework 上传文件时出现错误 "No file was submitted.",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53386945/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com