Во время ручного запроса POST я получаю ошибку в заголовке.Изменение request.FILES['myfile']
на request.FILES.get('myfile')
не помогло.Я понятия не имею, почему это происходит.Я пытался изменить атрибуты формы, но это тоже не помогло.
РЕДАКТИРОВАТЬ: Это должно быть что-то в java-скрипте, так как комментирование делает строку request.FILES ['myfile'] pass.
Мое представление:
def generate_random_user(request):
if (request.method == 'POST'):
text_info = request.POST.get('text_input')
myfile = request.FILES['myfile']
fs = FileSystemStorage()
filename = fs.save(myfile.name, myfile)
local_file_path = os.path.join(settings.MEDIA_ROOT, filename)
album = Album(local_file_path, text_info)
task = album.slice.delay(album)
songs_titles = album.songs_titles
#converted_files_urls = [fs.url(path) for path in songs_paths]
return HttpResponse(json.dumps({'task_id': task.id}), content_type='application/json')
return render(request, 'index.html')
Индекс HTML:
<html>
<head>
<title>Celery Demo</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
</head>
<body style="text-align: center;">
<h1>Generate Random Users</h1>
<progress id="progress-bar" value="0" max="100" style="display:none; margin-bottom: 1em;"></progress>
<form method="post" enctype="multipart/form-data">
{% csrf_token %}
<input type="file" name="myfile">
<br><textarea name="text_input" cols="40" rows="15" ></textarea>
<br><button id="submit_btn" type="submit" align="center" >Upload and slice.</button>
</form>
<script type="text/javascript">
var frm = $('form');
var button = $('#submit_btn');
var pgrbar = $('#progress-bar');
button.click(function () {
$.ajax({
type: frm.attr('method'),
url: frm.attr('action'),
data: frm.serialize(),
success: function (data) {
if (data.task_id != null) {
get_task_info(data.task_id);
}
},
error: function (data) {
console.log("Something went wrong!");
}
});
return false;
});
function get_task_info(task_id) {
$.ajax({
type: 'get',
url: '/get-task-info/',
data: {'task_id': task_id},
success: function (data) {
frm.html('');
if (data.state == 'PENDING') {
frm.html('Please wait...');
}
else if (data.state == 'PROGRESS' || data.state == 'SUCCESS') {
pgrbar.css('display', 'inline');
pgrbar.val(data.result.percent);
frm.html('User created ' + data.result.current + ' out of ' + data.result.total);
}
if (data.state != 'SUCCESS') {
setTimeout(function () {
get_task_info(task_id)
}, 1000);
}
},
error: function (data) {
frm.html("Something went wrong!");
}
});
}
</script>
</body>
</html>
Полная ошибка:
[17/Oct/2018 09:44:12] "GET /generate-user/ HTTP/1.1" 200 3024
Internal Server Error: /generate-user/
Traceback (most recent call last):
File "C:\Users\TommyYa\AppData\Local\Programs\Python\Python36\lib\site-packages\django\utils\datastructures.py", line 77, in __getitem__
list_ = super().__getitem__(key)
KeyError: 'myfile'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\Users\TommyYa\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\handlers\exception.py", line 34, in inner
response = get_response(request)
File "C:\Users\TommyYa\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\handlers\base.py", line 126, in _get_response
response = self.process_exception_by_middleware(e, request)
File "C:\Users\TommyYa\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\handlers\base.py", line 124, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "D:\Programowanie\PYTHON\Django\DivideAudio\audio_app\views.py", line 15, in generate_random_user
myfile = request.FILES['myfile']
File "C:\Users\TommyYa\AppData\Local\Programs\Python\Python36\lib\site-packages\django\utils\datastructures.py", line 79, in __getitem__
raise MultiValueDictKeyError(key)
django.utils.datastructures.MultiValueDictKeyError: 'myfile'
[17/Oct/2018 09:44:26] "POST /generate-user/ HTTP/1.1" 500 16547
Шаблоны URL:
urlpatterns = [
path('admin/', admin.site.urls),
path('generate-user/', views.generate_random_user),
path('get-task-info/', views.get_task_info),
]
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)