[FIXED] Copy file into another folder with django?

Issue

You must upload your profile picture to a separate folder in Django. So there is a folder for each account and profile pictures should be moved to a specific folder. How can I do that?

Here is my uploadprofile.html

{% csrf_token %}

Here are the views in views.py

def upload image (request):
    img = request.FILES['avatar'] #get filenames here. this works

    # Now create a folder in the specified profile with your user ID. this also works
    If not os.path.exists('static/profile/' + str(request.session['user_id'])) :
        os.mkdir('static/profile/' + str(request.session['user_id']))


    # Now create the name of the path to store as a VARCHAR field. this also works
    Avatar = "../../static/profile/" + str(request.session['user_id']) + "/" + str(img)

    #Then you need to copy the img file to the folder you created

    return redirect (request, "myapp/upload.html")
 

Solution

By looking at Django docs what you get when you do img = request.FILES['avatar'] is a file descriptor that points to an open file with your image.

Then you should to dump the contents in your actual avatar path, right?

#Here is where I create the name of the path to save as a VARCHAR field, THIS WORKS TOO
avatar = "../../static/profile/" + str(request.session['user_id']) + "/" + str(img)
# # # # # 
with open(avatar, 'wb') as actual_file:
    actual_file.write(img.read())
# # # # #    
return redirect(request, 'myapp/upload.html')

Beware: the code is untested.

Answered By – BorrajaX

Answer Checked By – David Goodson (Easybugfix Volunteer)

Leave a Reply

(*) Required, Your email will not be published