After reading other questions on a similar topic, I still do not understand what is wrong with this code.
I am testing code that uses the jQuery Form plugin. I added a call in the form of a template to display it for the first time so that the user can select a file and upload. But it never sends an AJAX request, so the section of code in the view is not executed. Although not shown here, the jQuery library and the jQueryForm plugin are indeed called.
Template:
<form id="uploadForm" method="post" enctype="multipart/form-data">
{% csrf_token %}
<input id="fileInput" class="input-file" name="upload" type="file">
{{ form.docfile }}
<span class="upload-message"></span>
<input type="submit" value="Upload" />
</form>
<script>
var message = '';
var options = {
type: "POST",
url: '/upload/file/',
error: function(response) {
message = '<span class="error">We\'re sorry, but something went wrong. Retry.</span>';
$('.upload-message').html(message);
$('fileInput').val('');
},
success: function(response) {
message = '<span class="' + response.status + '">' + response.result + '</span> ';
message = ( response.status == 'success' ) ? message + response.fileLink : message;
$('.upload-message').html(message);
$('fileInput').val('');
}
};
$('#uploadForm').ajaxSubmit(options);
</script>
View:
def upload(request):
response_data = {}
if request.method == 'POST':
if request.is_ajax:
form = UploaderForm(request.POST, request.FILES)
if form.is_valid():
upload = Upload(
upload=request.FILES['upload']
)
upload.name = request.FILES['upload'].name
upload.save()
response_data['status'] = "success"
response_data['result'] = "Your file has been uploaded:"
response_data['fileLink'] = "/%s" % upload.upload
return HttpResponse(json.dumps(response_data), content_type="application/json")
response_data['status'] = "error"
response_data['result'] = "We're sorry, but kk something went wrong. Please be sure that your file respects the upload conditions."
return HttpResponse(json.dumps(response_data), content_type='application/json')
else:
form = UploaderForm()
return render(request, 'upload.html', {'form': form})
It correctly calls the template for the first time, it displays the buttons, it runs the script again, but the form is invalid, so response_data is in error.
What am I missing?
Thanks Ricardo
source
share