I am gettting the error: [ErrorDetail(string='The submitted data was not a file. Check the encoding type on the form.', code='invalid')]
, for submitting an image/file.
I added the encryption type for the form 'multipart/form-data' same thing in Axios call too, but I still get the same error.
I have a model like this:
class MyModel(models.Model):
img = models.ImageField(upload_to='media',blank=False)
In views.py:
class MyModelView(viewset.ModelViewSet):
serializer_class = serializer.MyModelSerializer
def post(self,request):
data = serializer.MyModelSerializer(data=request.data)
print(data.is_valid()) # this is false, means there is an error
print(data.errors) #This one will display the error shown in the title of this question
if data.is_valid():
img = data.data['img']
return Response('Success')
return Response('Fail')
In serializer.py:
class MyModelSerializer(serializers.ModelSerializer):
class Meta:
model = MyModel
fields = '__all__'
In frontend side (React):
function ImgComp(){
let [img,setImg] = useState({'image':''}
let {image} = img
function handleChange(e){
setImg(
{
...img,[e.target.name]:e.target.value
}
)
}
function submitForm(e){
e.preventDefault()
axios.post('127.0.0.1:8000/mymodelurl/',img,{withCredentials:true,headers:{'Content-Type':'multipart/form-data'}})
return(
<div>
<form method='post' encType='multipart/form-data' onSubmit = {(e)=>submitForm(e)}>
<input type='file' value={image} name='img' onChange={(e)=>handleChange(e)}/>
</form>
</div>
}
}
If I debug the img I get something like:
C:\\fakepath\\img.png