Error: The uploaded image in Django REST API is missing a value

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));
    });
    }
}]);

Answer №1

When posting this JSON

data: {text: $scope.text, img: file}
, note that in the perform_create method, you are currently using self.request.data.get('file'). It seems like you should update this to

serializer.save(self.request.data.get('img'))

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Having trouble with installing Angular JS on my computer

On my machine, I have successfully installed node.js version v0.12.0. However, when attempting to run sudo npm install, I encountered the following errors: npm ERR! install Couldn't read dependencies npm ERR! Darwin 14.0.0 npm ERR! argv "node" "/usr/ ...

Exploring ways to loop through JSON object fields within a React application

There is a JSON representation of different categories and their respective subcategories that looks like this: [ { "category": "Mobiles", "sub": [ { "name": "Apple" }, { ...

What are the requirements for uploading files to a server directory?

Do you have a question regarding how to handle upload filename standards in your application? Let's say you have a system where various types of documents can be uploaded to the server and stored in a directory. Sometimes, the same document might even ...

Unknown CSS element discovered: bootstrap, gradient, carousel

I recently created a random quote app using javascript, jQuery, and bootstrap on Codepen. Everything worked perfectly there. However, when I organized the files, pushed them to git, and tried to view the app from Safari, I encountered some warnings and t ...

Retrieve information using AJAX via POST method

I find myself in a bit of a pickle at the moment. I've been researching for hours, and I still can't seem to figure out this seemingly basic issue. It would be greatly appreciated if someone could offer me some quick advice. So here's my dil ...

Avoid changing the format when sending a JSON string to Node

I am attempting to send JSON data to a Node application using a POST request, which will then be retrieved through a GET request. On the client side, I create a JSON string representing the model and send it to the server: $.post(serverURL, ko.mapping.toJ ...

What is causing my text to not appear in a single line?

Can someone help me figure out why my register and login options are overlapping? I'm pretty new to this so it might be a simple fix. Also, I'm trying to get the dropdown menu to appear right below the login text, but I'm facing some issues ...

The jQuery ajax function is not properly displaying or hiding the loader div

While attempting to call PHP code using a jQuery AJAX function, I encountered an issue where I wanted to display a loader div while the request was being sent and then hide the div once the request was complete. To simulate this scenario, I deliberately de ...

Tips for customizing the GeoDjango GeoJSON Serializer to incorporate model attributes

Here is a unique spin on how to include properties in JSON serialization, stemming from the following inquiry: from django.core.serializers.base import Serializer as BaseSerializer from django.core.serializers.python import Serializer as PythonSerializer ...

Tips for resetting the camera position on a canvas

Seeking advice on adjusting the camera position in my code. Any suggestions? I have played around with camera.position.set and added parameters for camera.position.x. function main() { const canvas = document.querySelector('#c'); const rend ...

Retrieve geographical coordinates from image metadata using JavaScript

Seeking help with extracting the GPS Exif tag from images using NodeJS. The data is currently structured as follows: { "gps": { "GPSTimeStamp": [2147483647, 76, 41], "GPSLongitude": [76, 41, 56.622], "GPSLatitude": [30, 43, 8 ...

Use regular expressions and JavaScript to enclose a series of English letters within a wrapper

I am looking to enclose a series or cluster of consecutive English characters within a <span> tag. In simpler terms, I aim to alter the appearance of English language in my writing. Therefore, I need to identify English characters and surround them ...

The placeholder attribute for input types does not display consistently across all browsers

I am experiencing an issue with the placeholder text in my input field. <input type="text" name='linkLabel{{index}}' autocomplete="off" class="input-large tight-form-url last remove-cross" required="required" placeholder="{{'linkLabel&ap ...

Create unique error messages using Vue validators

Two fields named text and email are included in my template. Below is the structure of the template: HTML <!DOCTYPE html> <html> <head> <title>Vue - Validations</title> <script src="Libraries/vue/vue.min.js&qu ...

What is the safest way to convert a local file path to a file:// URL in Node.js?

In my node.js application, I am faced with the task of converting local file paths into file:// urls. After some research, I came across the File URI scheme on Wikipedia and I believe that there must be a solution out there or perhaps even an npm module t ...

Leveraging nested relationships in Django Rest Framework for filtering data

When utilizing Django Rest Framework to build the API, I encountered a problem that I have been struggling with: How can I effectively filter associated tables? Below is the specific code snippet: models.py class Category(models.Model): name = models ...

Steps for generating a hierarchical menu utilizing data from a CSV file

I am looking to use a CSV file to structure the menu on my webpage. Could someone assist me in creating a nested menu using JavaScript with the provided CSV data? The columns consist of: Level, Menu name, URL 0;"Service"; 1;"Service 1";"http://some-url- ...

Setting `throwIfNamespace=true` in the `.babelrc` file for a `create-react-app` project

Running into a bit of a snag here. I thought setting up a simple app would be smooth sailing, but it seems that's not the case. I created an app using the latest create-react-app and decided to add a <gcse:search> tag. However, I encountered the ...

Fuzzy text in drop-down box on Chrome, clear on Firefox

I've encountered an issue with a dropdown menu in Google Chrome where the content appears blurry, while it displays correctly in Firefox. The problem arises when the dropdown exceeds a certain height, and I've tried setting a max-height with over ...

Toggle button visibility on ng-repeat item click

Hello everyone, I'm encountering an issue with displaying and hiding buttons in ng-repeat. <div class="row" ng-repeat="item in items"> <button type="button" ng-click="add()">+</button> <button type="button" ng-click="remo ...