DRF The submitted data was not a file. Check the encoding type on the form - ImageField

0

I have the following model User:

class User(AbstractBaseUser, PermissionsMixin):
#... other attributes  
    photo = models.ImageField(upload_to='avatars', blank=True)

The basic serialization that I made of this model is:

class UserSerializer(serializers.ModelSerializer):
    team = serializers.StringRelatedField()

    def setup_eager_loading(queryset):
      queryset = queryset.select_related('team',)

    class Meta:
        model = User
        fields = ('url', 'username','password','first_name','last_name',
        'photo','team','position','last_login',)

The team field is a foreign key in the User model, which is serialized to optimize its performance in queries to the database when there are relations, with the setup_eager_loading function method.

The viewset function of the User model is:

from rest_framework import viewsets
from rest_framework import filters

from .models import User
from .serializers import UserSerializer

# Viewsets define the behavior of the view
class UserViewSet(viewsets.ModelViewSet):
    """
    API endpoint that allows users to be viewed or edited.
    """
    queryset = User.objects.all().order_by('-date_joined')
    serializer_class = UserSerializer
    filter_fields = ('username','is_player', 'first_name','last_name','team','email',)

When I go to an instance of a user in my serialized api via Django Rest Framework, and I want to update some data (any) of that instance through pure json data (json raw data media type: application / json) I get this message:

How can I manipulate at the CRUD level the User objects serialized in my api through pure json data in Django Rest Framework without having coding errors?

    
asked by bgarcial 29.10.2016 в 02:12
source

1 answer

1

That happens because you are waiting for a file to be sent to the photo field, if you are going to do an edition from the browsable API, it sends a POST and this is resolved by "replacing" all the values of the model by which you are sending and how you send application / json instead of multipart throws the error of could not decode that file field.

If you make the request with AJAX, cURL, etc ... you could send a PATCH and in this way update partially and it would work without problem.

I recommend you use Postman to make the requests since the DRF Browsable API falls short.

Greetings. I hope I have helped you.

EDIT:

How to make the request using jQuery AJAX:

var username = 'mauricio';
$.ajax({
   url: '/api/users/'+username+'/',
   method: 'PATCH', 
   data : {
      first_name: 'Mauricio Alberto'
   },
   success: function(response){
     console.log(response);
   },
   error: function(response){
     console.warn(response);
   }
});

This example is partially updated using PATCH, that is, only the first_name field is modified.

    
answered by 29.10.2016 в 07:49