I am playing around with django's fileupload and got their documentation in the example to work. Now, I would like to modify the response by using a JsonResponse like so:
def upload_file(request):
if request.method == 'POST':
form = UploadFileForm(request.POST, request.FILES)
if form.is_valid():
handle_uploaded_file(request.FILES['file'])
# this is default as in django 1.7 docs:
# return HttpResponseRedirect('/success/url/')
# this is what I want to implement
return JsonResponse({'foo': "bar"})
else:
form = UploadFileForm()
return render_to_response('upload.html', {'form': form})
Now, what I'd like is to show this return JsonResponse({'foo': "bar"})
on my template. However, I am not sure how to get
this variable on the JS side. For example, something like:
<script type='text/javascript'>
var data = {{ foo }};
console.log(data);
</script>
.. but this does not work - I am not sure how I could get the data in JS using the JsonResponse
object from django.
Any help with this would be great!
MORE INFO
Since I am using dropzone.js to process my file upload, I have the following JS code:
## load dropzone.js
<script type="text/javascript">
Dropzone.options.myDropzone = {
paramName: "file_field", // The name that will be used to transfer the file
maxFilesize: 20, // MB
// Prevents Dropzone from uploading dropped files immediately
autoProcessQueue : true,
clickable : true,
init: function() {
this.on("success", function(file, responseText) {
// Handle the responseText here. For example, add the text to the preview element:
file.previewTemplate.appendChild(document.createTextNode({{django_json}}));
});
}
};
</script>
The JS snippet that you have posted shows where you need to handle the returned JSON. The data is passed to your success function as "responseText":
this.on("success", function(file, responseText) {
file.previewTemplate.appendChild(responseText);
});
but you will probably want to use JSON.parse
to convert it to actual JS objects.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.