Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django REST, uploaded image has null value

I have simple app with Django REST and Angular on frontend and I have problem with image upload.
my model:

class Photo(models.Model):

    img = models.ImageField(upload_to='photos/', max_length=254)
    text = models.CharField(max_length=254, blank=True)

When I sending image via form, text uploaded well, but image has null value.
responce from browser:

{"img":null,"text":"test"}

here is printed self.data.request when I uploaded image:

QueryDict: {'text': ['test'], 'InMemoryUploadedFile: filename.jpg (image/jpeg)]}

Serializer is just simple ModelSerializer with two model fields.
view:

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('file'))

photo_router = DefaultRouter()
photo_router.register(r'photo', PhotoViewSet)

For image upload I use lib ng-file-upload, I tried another way to upload and image was null too.
angular code:

var app = angular.module('myApp', ['ngRoute', 'ngFileUpload']);

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';
}]);
app.controller('MyCtrl', ['$scope', 'Upload', '$timeout', function($scope, Upload, $timeout) {
    $scope.uploadPic = function(file) {
    file.upload = Upload.upload({
        url: '/api/photo/',
        data: {text: $scope.text, img: file},
    });

    file.upload.then(function (response) {
      $timeout(function () {
        file.result = response.data;
      });
    }, function (response) {
      if (response.status > 0)
        $scope.errorMsg = response.status + ': ' + response.data;
    }, function (evt) {
      file.progress = Math.min(100, parseInt(100.0 * evt.loaded / evt.total));
    });
    }
}]);
like image 222
Ivan Semochkin Avatar asked Mar 09 '16 23:03

Ivan Semochkin


1 Answers

You are posting this json data: {text: $scope.text, img: file}, but in the perform_create method you call self.request.data.get('file'). I think you have to change this to

serializer.save(self.request.data.get('img'))
like image 51
ilse2005 Avatar answered Oct 14 '22 01:10

ilse2005