I am currently facing an issue with image upload in my simple app built with Django REST on the backend and Angular on the frontend.
Here is a snippet of 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 try to upload an image via a form, the text gets uploaded successfully but the image field remains null.
The response from the browser shows:
{"img":null,"text":"test"}
When I printed self.data.request
after uploading the image, here is what was displayed:
QueryDict: {'text': ['test'], 'InMemoryUploadedFile: filename.jpg (image/jpeg)]}
The serializer I am using is a simple ModelSerializer
with two model fields.
Below is the code for the 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)
I have been using the library ng-file-upload for image uploads in Angular. However, even after trying different approaches, the image field still remains null.
Here is the Angular code snippet:
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));
});
}
}]);