我需要将配置文件图像上传到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>
这是我在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')
你可以将一个callable传递给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中有更多信息,也是一个例子,尽管与我上面发布的相似。
通过查看Django docs,当你执行img = request.FILES['avatar']
时,你会得到一个文件描述符,指向一个带有你图像的打开文件。
然后你应该将内容转储到你真正的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')
注意:代码未经测试。