I am trying to send a form from Vue.js to Django with DRF. But the response is 400 Patch error:
{"file":["The submitted data was not a file. Check the encoding type on the form."]}
It is my template in Vue.js: Template:
<input type="file" id="file" ref="file" class="input is-rounded" v-on:change="handleFileUpload()"/>
And here is Vue methods. I send enctype: 'multipart/form-data' and I think that I am using the correct way to send the file. Anyway, I think that here is the problem, maybe this.file is not sending the file correctly.
HTTP is a constant to Axios: "const HTTP = axios.create({})"
methods: {
handleFileUpload(){
this.file = this.$refs.file.files[0];
},
create: function () {
this.token = this.$store.state.access_token;
HTTP({
method: 'PATCH',
url: 'tickets/create/',
enctype: 'multipart/form-data',
headers: {
'Authorization': `Bearer ${this.token}`,
},
data: {
file:this.file,
}
})
.then(response => { ...
And here my view.py method:
@csrf_exempt
@api_view(['GET', 'POST','PATCH'])
def Create(request):
parser_classes = (FileUploadParser,)
if request.method == 'PATCH' or request.method == 'POST':
serializer = CreateTicketSerializer(
Tickets,
data=request.data
)
serializer.is_valid(raise_exception=True)
if serializer.is_valid():
serializer.save()
return Response(serializer.data, status=status.HTTP_201_CREATED)
else:
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
#Return this if request method is not POST
return Response({'ok': 'false'}, status=status.HTTP_200_OK)
And my Serializer:
class CreateTicketSerializer(serializers.ModelSerializer):
"""Ticket serializer."""
file = serializers.ImageField(required=False,max_length=None, use_url=True)
class Meta:
model = Tickets
fields = (
'file',
)