I want to submit a form to upload either a csv file or an excel file, and provide additional information provided in the form, e.g. text.
For defining the form and sending the request I use React Bootstrap with axios, and for the api I'm using Django 2.2 with rest-framework.
request.FILES
is always an empty dict, even if I try setting the Content-Type header to multipart/form-data
, and then additionally nothing is found in the post data of the request, and printing request.data.get('information') below shows None
in the Django log. Please help, any support will be greatly appreciated.
See below for code snippets.
Form definition in render():
<form onSubmit={this.handleSubmit}>
<FormGroup>
<Form.Label>Upload file</Form.Label>
<Form.Control type="file" onChange={this.handleFile}></Form.Control>
</FormGroup>
<Button block bssize="large" disabled={!this.validateForm()} type="submit">
Submit
</Button>
</form>
Handling file change:
handleFile = event => {
event.preventDefault();
const fileToUpload = event.target.files[0]
this.setState({
fileToUpload: fileToUpload
})
}
Sending the request:
const payload = {
file: this.state.fileToUpload,
information: "somedata"
}
const contentType = "multipart/form-data"
let accessToken = token
var headers = {"Authorization" : `Bearer ${accessToken}`}
headers['Content-Type'] = contentType
const response = await axios({
method: "post",
data: payload,
url: url,
headers: headers
});
Django endpoint definition:
class RegisterData(views.APIView):
parser_classes = (parsers.JSONParser, parsers.MultiPartParser)
def post(self, request):
for file in request.FILES.values():
print(file)
info = request.data.get('information')
print(info)
return Response({"success": "Good job, buddy"})