[Django]-Python/Django โ€“ using a view method on an upload file

3๐Ÿ‘

โœ…

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 the name from the <input type="file" name="" />. Each
value in FILES is an UploadedFile.

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.

๐Ÿ‘คRahul Gupta

Leave a comment