I new in REST and trying to create simple app, with one model and two fields CharField
, ImageField
.
model:
class Photo(models.Model):
img = models.ImageField(upload_to='photos/', max_length=254)
text = models.CharField(max_length=254, blank=True)
serializers:
class PhotoSerializer(serializers.ModelSerializer):
class Meta:
model = Photo
fields = ('img','text')
views:
class PhotoViewSet(viewsets.ModelViewSet):
queryset = Photo.objects.all()
serializer_class = PhotoSerializer
photo_router = DefaultRouter()
photo_router.register(r'photo', PhotoViewSet)
urls:
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^api/', include(photo_router.urls)),]
POST and GET works well in /api/photo/
I ask similar question before and I was definitely sure, problem was in frontend, with AngularJS, I using AngularJS first time too. But I think now, maybe problem with my server app.
angular code:
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 controller works well, I recieve all my images:
app.controller('getController', ['$scope', '$http', function($scope, $http){
$http.get('/api/photo/').success(function(data){
$scope.photos = data;
}).error(function(data) {
$scope.photos = data;
});
}]);
For file uploading I used this guide
Here is code from guide:
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 code:
<div ng-controller = "myCtrl">
<input type="file" file-model="myFile"/>
<button ng-click="uploadFile()">upload me</button>
</div>
When I upload files by this form I have:
POST http://127.0.0.1:8000/api/photo/ 400 (Bad Request)
in responce:
img: ["No file was submitted."]
Please help at least to understand, where my problem is, on my REST or in Angular. And how I can debug this? I spend all day for trying find solution. I think I just clearly don't understand how REST api need to looks.
UPD
I'm trying to use ng-file-upload and still have 400 responce status.
I decide is problem with serializer, I overide POST method in view, but I think I did it wrong:
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)
Here is full request data from web tool:
General
Request URL:http://127.0.0.1:8000/api/photo/
Request Method:POST
Status Code:400 Bad Request
Remote Address:127.0.0.1:8000
Response Headers
Allow:GET, POST, HEAD, OPTIONS
Content-Type:application/json
Date:Wed, 09 Mar 2016 14:46:44 GMT
Server:WSGIServer/0.2 CPython/3.4.3
Vary:Accept, Cookie
X-Frame-Options:SAMEORIGIN
Request Headers
Accept:application/json, text/plain, /
Accept-Encoding:gzip, deflate
Accept-Language:ru-RU,ru;q=0.8,en-US;q=0.6,en;q=0.4
Connection:keep-alive
Content-Length:16635
Content-Type:multipart/form-data; boundary=---- WebKitFormBoundarytci4JfMISlMXwzFw
Cookie:sessionid=f5nyqdclupgi44zyqbmo3gkenum9k0cj; csrftoken=E0DuVDs5KrV0rSMuD5wC86RPO0QP4AgT
Host:127.0.0.1:8000
Origin:http://127.0.0.1:8000
Referer:http://127.0.0.1:8000/
User-Agent:Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.106 Safari/537.36
X-CSRFToken:E0DuVDs5KrV0rSMuD5wC86RPO0QP4AgT
Request Payload
------WebKitFormBoundarytci4JfMISlMXwzFw
Content-Disposition: form-data; name="file"; filename="2.jpg"
Content-Type: image/jpeg
------WebKitFormBoundarytci4JfMISlMXwzFw--
{"img":["No file was submitted."]}
– Ivan Semochkin