在尝试使用具有内容类型-标题中包含multipart / form-data的Postman上载文件时。我同时传递了两个字段,但是出现以下错误:
错误:{“ upload_to”:[“此字段为必填。”],“ file_object”:[“否 文件已提交。“]}
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())
]
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
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')
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)
请帮助...我不知道怎么了。
答案 0 :(得分:2)
我已按照以下方式更改了我的models.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)