2017-12-29 43 views
1

プロファイル画像をDjangoの別のフォルダにアップロードする必要があります。だから、私は各アカウントのためのフォルダがあり、プロファイルの画像は特定のフォルダに移動する必要があります。どうやってやるの?ここでファイルをdjangoで別のフォルダにコピーしますか?

は私のuploadprofile.html

<form action="{% url 'uploadimage' %}" enctype="multipart/form-data" method="POST"> 
    {% csrf_token %} 
    <input type="file" name="avatar" accept="image/gif, image/jpeg, image/png"> 
    <button type="submit">Upload</button> 
</form> 

そして、ここが私の見解は、あなたが得るimg = request.FILES['avatar']を行うときに何を得るDjango docsを見ることによってviews.py

def uploadimage(request): 
    img = request.FILES['avatar'] #Here I get the file name, THIS WORKS 

    #Here is where I create the folder to the specified profile using the user id, THIS WORKS TOO 
    if not os.path.exists('static/profile/' + str(request.session['user_id'])): 
     os.mkdir('static/profile/' + str(request.session['user_id'])) 


    #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) 

    #THEN I HAVE TO COPY THE FILE IN img TO THE CREATED FOLDER 

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

答えて

0

中ですファイル記述子は、画像とともに開いているファイルを指します。

次に、内容を実際のavatarパスにダンプする必要がありますか?

#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') 

注意:コードはテストされていません。

2

upload_toに発信可能な番号を渡すことができます。基本的には、呼び出し可能な戻り値があれば、画像はそのパスにアップロードされます。

例:

def get_upload_path(instance, filename): 
    return "%s/%s" % (instance.user.id, filename) 

class MyModel: 
    user = ... 
    image = models.FileField(upload_to=get_upload_path) 

私は上記の投稿何に似ているが、よりdocs内の情報と例は、あまりにもあります。

関連する問題