Abdul Rehman
Abdul Rehman

Reputation: 5684

How to get the name of uploaded file in Django

I have seen some question about it already but these couldn't solve my issue, that's why I'm asking a new question.So, don't mark this as duplicate, please!

Using Python(3.6) & Django(1.10) I'm trying to get the name of uploaded file, but it returns

AttributeError: 'NoneType' object has no attribute 'name'

Here's what I have tried: From models.py

sourceFile = models.FileField(upload_to='archives/', name='sourceFile', blank=True)

From HTML template:

<div class="form-group" hidden id="zipCode">
                    <label class="control-label" style="font-size: 1.5rem; color: black;">Select File</label>
                    <input id="sourceFile" name="sourceFile" type="file" class="file" multiple
                           data-allowed-file-extensions='["zip"]'>
                    <small id="fileHelp" class="form-text control-label" style="color:black; font-size: .9rem;">
                        Upload a Tar or Zip
                        archive which include Dockerfile, otherwise your deployment will fail.
                    </small>
                </div>

From views.py:

if form.is_valid():
               func_obj = form
               func_obj.sourceFile = form.cleaned_data['sourceFile']
               func_obj.save()
               print(func_obj.sourceFile.name)

what's wrong here?

Help me, please!

Thanks in advance!

Upvotes: 2

Views: 2922

Answers (1)

Atto Allas
Atto Allas

Reputation: 610

To get the filename, you simply use the request.FILES dictionary (I assume that there is only 1 file being uploaded)

Example:

try:
    print(next(iter(request.FILES))) # this will print the name of the file
except StopIteration:
    print("No file was uploaded!")

Note that this requires that the files were sent as a part of a form by the POST method.

To change their name to a random string, I recommend uuid.uuid4, as this generates a random string that is VERY unlikely to collide with anything already there. Also, you need to edit your upload_to= section of your sourceFile model by providing a function to generate the name:

# In models.py

def content_file_name(instance, filename):
    filename = "{}.zip".format(str(uuid.uuid4().hex))
    return os.path.join('archives', filename)

# later....

sourceFile = models.FileField(upload_to=content_file_name, name='sourceFile', blank=True)

Hope this helps!

Upvotes: 2

Related Questions