Reputation: 95
I'm trying to send an image from frontend using ajax to backend using django rest framework without result.
The response error is: {"detail":"Unsupported media type \"image/png\" in request."}
where instead of "image/png" I tried a lot o different types. (the img I'm sending is a png)
HTML:
<input type="file" name="" id="profilepic" enctype="multipart/form-data" accept="image/*">
<label id="uploadBtn" for="profilepic">Choose your profile photo</label>
JS:
Note that first I was sending all the nested data as JSON but later I splitted to send the img separeted.
var my_data = { "user_url": user_url, "user": username, "atoms": [atom_dict] };
$.ajax({
url: origin + '/boonds_api' + userurl,
type: 'PUT',
contentType: "application/json",
data: JSON.stringify(my_data),
success: function (result) {
console.log(my_data);
}
});
// Until here everything is fine sebding data to backend
// Only img
my_img = $('#profilepic')[0].files[0]
var my_data = {"atoms": {"img":my_img}};
$.ajax({
url: origin + '/boonds_api' + userurl,
type: 'PUT',
contentType: "image/png",
data: JSON.stringify(my_data),
success: function (result) {
console.log(my_data);
}
});
DJANGO
models.py
class Atom(models.Model):
name = models.CharField(max_length=128,blank=True)
bio = models.TextField()
img = models.ImageField(null=True, blank=True, upload_to='users_app')
user_account = models.ForeignKey(UserAccount, on_delete=models.CASCADE, null=True, blank=True, related_name="atoms")
def __str__(self):
return self.name
views.py
class UserAccountViewSet(viewsets.ModelViewSet):
queryset = UserAccount.objects.all()
serializer_class = UserAccountSerializer
lookup_field = "user_url"
permission_classes = [IsOwnerOrReadOnly]
def update(self, request, *args, **kwargs): # update = PUT
partial = kwargs.pop('partial', False)
instance = self.get_object()
serializer = self.get_serializer(
instance, data=request.data, partial=partial)
serializer.is_valid(raise_exception=True)
self.perform_update(serializer)
return Response(serializer.data)
serializers.py
I tried also different solutions to accept the image but not sure if the error is here, in models or in ajax.
from drf_writable_nested import WritableNestedModelSerializer # Enable write nested
from .models import *
from drf_base64.fields import Base64ImageField
class AtomSerializer(serializers.HyperlinkedModelSerializer, WritableNestedModelSerializer):
boonds = BoondSerializer(many=True,required=False)
img = Base64ImageField(max_length=None, use_url=True, required=False)
class Meta:
model = Atom
fields = ["name","bio", "img", "boonds"]
Upvotes: 2
Views: 1554
Reputation: 95
I solved it avoiding using drf (serializer) and just creating a new ednpoint with an update view (UpdateView):
class yourImageView(UpdateView):
model = YourModel
def post(self, request, *args, **kwargs):
img = self.request.FILES["my_img"]
YourModel.img = img
YourModel.save()
Ajax:
var form = new FormData();
form.append('my_img', my_img);
$.ajax({
type: 'POST',
url: origin + '/new_endpoint/' + userdata.user_id + "/",
data: form,
contentType: false,
processData: false
})
Upvotes: 2