Минимальный пример для загрузки файла,
views.py
def upload(request):
if request.method == 'GET':
f = FileUpload()
elif request.method == 'POST':
import ipdb;
ipdb.set_trace()
f = FileUpload(request.POST, request.FILES)
if f.is_valid():
uploaded_file = f.cleaned_data['file_object']
# manipulate file here.
return render(request, 'upload.html', {'form': f})
urls.py
urlpatterns = [
path('', views.home, name='home'),
path('upload/', views.upload, name='uoload'),
path('admin/', admin.site.urls),
]
upload. html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
$( document ).ready(function() {
alert( "ready!" );
$("#upload-btn").click(function (event) {
$.ajax({
type: "POST",
enctype: 'multipart/form-data',
url: "/upload/",
data: data,
processData: false,
contentType: false,
cache: false,
timeout: 600000,
success: function (data) {
$("#result").text(data);
console.log("SUCCESS : ", data);
$("#btnSubmit").prop("disabled", false);
},
error: function (e) {
$("#result").text(e.responseText);
console.log("ERROR : ", e);
$("#btnSubmit").prop("disabled", false);
}
});
});
});
</script>
</head>
<body>
<form action="/upload/" method="post" id="file-upload-form" enctype="multipart/form-data"> {% csrf_token %}
{{ form }}
<button type="submit" class="btn btn-primary" id='upload-btn'>Upload</button>
</form>
</body>
</html>