我正在使用 Django Rest Framework 和 AngularJs 上传文件。我的 View 文件如下所示:
class ProductList(APIView):
authentication_classes = (authentication.TokenAuthentication,)
def get(self,request):
if request.user.is_authenticated():
userCompanyId = request.user.get_profile().companyId
products = Product.objects.filter(company = userCompanyId)
serializer = ProductSerializer(products,many=True)
return Response(serializer.data)
def post(self,request):
serializer = ProductSerializer(data=request.DATA, files=request.FILES)
if serializer.is_valid():
serializer.save()
return Response(data=request.DATA)
由于post方法的最后一行应该返回所有数据,所以我有几个问题:
- 如何检查
request.FILES
中是否有内容? - 如何序列化文件字段?
- 我应该如何使用解析器?
最佳答案
Editor's note:
- This answer uses
pre_save
, which no longer exists in Django REST framework 3.0.- In a sufficiently new version of Django REST framework,
MultiPartParser
should be available by default, which allows uploading file with no special handling. See an answer below for an example.
我正在使用相同的堆栈,并且还在寻找文件上传的示例,但我的情况更简单,因为我使用的是 ModelViewSet 而不是 APIView。关键是 pre_save 钩子(Hook)。我最终将它与 angular-file-upload 模块一起使用,如下所示:
# Django
class ExperimentViewSet(ModelViewSet):
queryset = Experiment.objects.all()
serializer_class = ExperimentSerializer
def pre_save(self, obj):
obj.samplesheet = self.request.FILES.get('file')
class Experiment(Model):
notes = TextField(blank=True)
samplesheet = FileField(blank=True, default='')
user = ForeignKey(User, related_name='experiments')
class ExperimentSerializer(ModelSerializer):
class Meta:
model = Experiment
fields = ('id', 'notes', 'samplesheet', 'user')
// AngularJS
controller('UploadExperimentCtrl', function($scope, $upload) {
$scope.submit = function(files, exp) {
$upload.upload({
url: '/api/experiments/' + exp.id + '/',
method: 'PUT',
data: {user: exp.user.id},
file: files[0]
});
};
});
关于python - Django Rest 框架文件上传,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20473572/