class Photo(models.Model):
img = models.ImageField(upload_to='photos/', max_length=254)
text = models.CharField(max_length=254, blank=True)
class PhotoSerializer(serializers.ModelSerializer):
class Meta:
model = Photo
fields = ('img','text')
意见:
class PhotoViewSet(viewsets.ModelViewSet):
queryset = Photo.objects.all()
serializer_class = PhotoSerializer
photo_router = DefaultRouter()
photo_router.register(r'photo', PhotoViewSet)
URL:
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^api/', include(photo_router.urls)),]
POST和GET在/api/photo/
中工作得很好我以前问过类似的问题,我肯定,问题是在前面,用AngularJS,我也是第一次使用AngularJS。但我现在想,可能是我的服务器应用程序出现了问题。
角代码:
var app = angular.module('myApp', ['ngRoute', 'angularFileUpload']);
app.config(function ($routeProvider) {
$routeProvider
.when('/', {
templateUrl: 'http://127.0.0.1:8000/static/js/angular/templates/home.html'
})
});
app.config(['$httpProvider', function($httpProvider) {
$httpProvider.defaults.xsrfCookieName = 'csrftoken';
$httpProvider.defaults.xsrfHeaderName = 'X-CSRFToken';
}]);
GET控制器工作良好,我累犯了我所有的图像:
app.controller('getController', ['$scope', '$http', function($scope, $http){
$http.get('/api/photo/').success(function(data){
$scope.photos = data;
}).error(function(data) {
$scope.photos = data;
});
}]);
对于文件上传,我使用了本指南
,这里是指南中的代码:
app.directive('fileModel', ['$parse', function ($parse) {
return {
restrict: 'A',
link: function(scope, element, attrs) {
var model = $parse(attrs.fileModel);
var modelSetter = model.assign;
element.bind('change', function(){
scope.$apply(function(){
modelSetter(scope, element[0].files[0]);
});
});
}
};
}]);
app.service('fileUpload', ['$http', function ($http) {
this.uploadFileToUrl = function(file, uploadUrl){
var fd = new FormData();
fd.append('file', file);
$http.post(uploadUrl, fd, {
transformRequest: angular.identity,
headers: {'Content-Type': undefined}
})
.success(function(){
})
.error(function(){
});
}
}]);
app.controller('myCtrl', ['$scope', 'fileUpload', function($scope, fileUpload){
$scope.uploadFile = function(){
var file = $scope.myFile;
console.log('file is ' );
console.dir(file);
var uploadUrl = "/api/photo/";
fileUpload.uploadFileToUrl(file, uploadUrl);
};
}]);
html代码:
<div ng-controller = "myCtrl">
<input type="file" file-model="myFile"/>
<button ng-click="uploadFile()">upload me</button>
</div>
class PhotoViewSet(viewsets.ModelViewSet):
queryset = Photo.objects.all()
serializer_class = PhotoSerializer
def post(self, request, format=None):
serializer = PhotoSerializer(data=request.DATA)
if serializer.is_valid():
serializer.save()
return Response(serializer.data, status=status.HTTP_201_CREATED)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
查看Django Rest框架文件上传页面中提供的示例:
您需要在视图中添加相关的parser_classes
,并重写perform_create
函数,以便从POST数据中获取文件
:
class PhotoViewSet(viewsets.ModelViewSet):
queryset = Photo.objects.all()
serializer_class = PhotoSerializer
parser_classes = (MultiPartParser, FormParser,)
def perform_create(self, serializer):
serializer.save(img=self.request.data.get('img'))
# do note that at this time `text` information is not available
因为,我们发布formdata
,我们使用以下解析器(链接):
parser_classes = (MultiPartParser, FormParser,)
fd.append('img', file);