在handlig POST请求期间,标题出现错误。将request.FILES['myfile']
更改为request.FILES.get('myfile')
并没有帮助。我不知道为什么会这样。
我尝试过更改表单属性,但这也无济于事。
编辑:它必须在Java脚本中,因为注释掉会使行request.FILES ['myfile']通过。
我的观点:
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
网址模式:
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)
答案 0 :(得分:0)
首先,查看javascript发送了什么值:试试:
<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(),
**alert(data) // see the data pass or console.log(data)**
success: function (data) {
if (data.task_id != null) {
get_task_info(data.task_id);
}
},
error: function (data) {
console.log("Something went wrong!");
}
});
return false;
});
检查输出数据是否正确。