我需要复制文件:
<form action="test_edit_info" method="POST" enctype="multipart/form-data">
{%csrf_token%}
<input type="file" name="avatar">
<input type="submit" value="Register"/>
</form>
到我的静态 -dir (只需将模板中的表格中的文件复制到STATIC中)
视图:中的
def test_edit_info(request):
if request.method == "POST" :
new_ava = request.FILES['avatar']
print "new ava: ",new_ava #return file-name
c = {}
c.update(csrf(request))
return render(request, "test_edit_personal_information.html")
只需将文件从模板复制到静态目录。没有任何形式和模型。帮助,请。 THX。
答案 0 :(得分:0)
首先,static
dir就像它的名字所说:STATIC。它只包含静态文件,如自定义js,静态图像,CSS ...
如果您要上传文件,请使用media
目录。
观点: 不要忘记导入设置
from django.conf import settings
if request.method == 'POST':
if 'avatar' in request.FILES:
file = request.FILES['avatar']
# Other data on the request.FILES dictionary:
# filesize = len(file['content'])
# filetype = file['content-type']
filename = file['filename']
fd = open('%s/%s' % (settings.MEDIA_ROOT, filename), 'wb')
fd.write(file['content'])
fd.close()
#return ...
答案 1 :(得分:0)
thx,但有错误: 'InMemoryUploadedFile'对象没有属性' getitem ' filename = file ['filename']
那么,这个怎么样?
from django.core.files.storage import default_storage
from django.core.files.base import ContentFile
def test_edit_info(request):
if request.method == 'POST':
if 'avatar' in request.FILES:
file = request.FILES['avatar']
default_storage.save("E:/reg_extend_2/static/img/avatars/%s"%(file), ContentFile(file.read()))
c = {}
return render(request, "test_edit_personal_information.html")