Answer the question
In order to leave comments, you need to log in
django file transfer?
I need to upload a file from Django to a web page. The file is being transferred. But it does not open in Excel, and it is visually visible that the file encoding is different.
The greatly simplified code looks like this (we do not pay attention to the serializer and pk transmission - this does not affect the logic):
Server side:
class CEIViewset(GenericViewSet):
queryset = CompetitionCEI.objects.all()
permission_classes = (permissions.IsAuthenticated,)
serializer_class = CompetitionCEISerializer
@action(detail=False, methods=['POST'], permission_classes=(permissions.IsAuthenticated, ))
def export_to_xls(self, request):
ser = self.serializer_class(data=request.data)
if ser.is_valid():
pk = ser.validated_data.get('pk')
with open(os.path.join(settings.BASE_DIR, 'data', 'sample.xls'), 'rb') as f:
data = f.read()
response = HttpResponse(data, content_type='application/xls; charset=utf-8')
response['Content-Disposition'] = 'attachment; filename="sample.xls"'
return response
function exportXLS(pk) {
$.ajax({
method: 'POST',
url: '/api/v1/cei/export_to_xls/',
csrfmiddlewaretoken: '{{ csrf_token }}',
contentType: 'application/json',
responseType: 'blob',
data: JSON.stringify({
pk: {{ object.pk }},
}),
success: function (response) {
}
}).done(function(response){
var newBlob = new Blob([response], {type: "application/xls"});
const data = window.URL.createObjectURL(newBlob);
var link = document.createElement('a');
link.href = data;
link.download="sample.xls";
link.click();
})
}
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question