4
votes

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--

1
Give this directive a try: github.com/danialfarid/ng-file-upload For the backend, I'd recommend using the debugger, so you can actually look into the request object.fodma1
@fodma1 you mean django-debug-toolbar? I forget about it. And I tryied ng-file-upload, I write it in questionIvan Semochkin
Nope, I meant that you could run your python code in your IDE (eg. IntelliJ/Pycharm/Eclipse) and all of these have debug mode, where you can inspect the variables in each linefodma1
And you can also check your post request in Chrome dev toolbarfodma1
@fodma1 I post it in quetion, sure I check my dev toolbar. And I have responce {"img":["No file was submitted."]}Ivan Semochkin

1 Answers

2
votes

Looking at the example provided on the page Django Rest Framework File Upload:

You will need to add relevant parser_classes in the view and also override the perform_create function to get the file from the POST data:

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

Since, we are posting FormData we use following parsers (link):

parser_classes = (MultiPartParser, FormParser,)  

Also, notice that serializer.is_valid() is throwing error because it is not getting the img field in the post data. You need to set img instead of file field:

fd.append('img', file);