Reputation: 993
I have this view:
def index(request):
file = open("SK ✌😜✌.txt", encoding="UTF-8")
data = file.read()
file.close()
lines = data.split("\n")
...More code...
In this view i open a file from the very first moment the app starts and i do some work on the file, is a story, and when i start the server and go to http://127.0.0.1:8000/(Name Of The App), i see all the work that i have done on that file.
What i want to do is to do that same work, starting with the reading of the file, BUT i want to do that with the file that the user uploads in that moment. I have this that i took from bootstrap:
<div class="form-group">
<label for="exampleInputFile">File input</label>
<input type="file" id="exampleInputFile">
</div>
I guess i have to use in some way the id of the input but i`m not really sure how to pass this file that the user uploads in the ui to the method that i have in my views.py
Any help will be really appreciated
Upvotes: 3
Views: 1254
Reputation: 47846
You need to have a name
attribute in your <input>
template code.
<input type="file" id="exampleInputFile" name="some_file">
Then to access the file in your view, you need to use request.FILES
attribute.
As per the Django docs on HttpRequest.FILES
attribute:
A dictionary-like object containing all uploaded files. Each key in
FILES
is thename
from the<input type="file" name="" />
. Each value inFILES
is anUploadedFile
.
Your code should be something like:
def index(request):
if request.method=="POST":
uploaded_file = request.FILES['some_file'] # get the uploaded file
# do something with the file
Note: request.FILES
will only contain data if the request method was POST
and the <form>
that posted to the request had enctype="multipart/form-data
. Otherwise, FILES
will be a blank dictionary-like object.
Upvotes: 3