Django 如何从数据中获取上传文件的名称?
我有以下文件处理功能:Django 如何从数据中获取上传文件的名称?,django,forms,file,python-3.x,Django,Forms,File,Python 3.x,我有以下文件处理功能: def handle_uploaded_file(f, person): with open(user_directory_path(person, f.name), 'w') as destination: for chunk in f.chunks(): destination.write(chunk) 我在表单保存方法中调用此函数: class CreateMessageForm(forms.Form): f
def handle_uploaded_file(f, person):
with open(user_directory_path(person, f.name), 'w') as destination:
for chunk in f.chunks():
destination.write(chunk)
我在表单保存方法中调用此函数:
class CreateMessageForm(forms.Form):
files = forms.FileField(widget=forms.ClearableFileInput(attrs={'multiple': True}))
...
def save(self):
...
for file in cleaned_data.get('files'):
handle_uploaded_file(file, self.person)
message.files.add(file)
但在发送此表单后,我有一个AttributeError:“bytes”对象没有属性“name”。我不明白怎么了。在docs uploadedfile中,对象具有此属性。在html表单中尝试此属性
<form enctype="multipart/form-data" method="post" action="/foo/">
我建议您在表单中使用
FileField
:
class MyForm(forms.Form):
file = forms.FileField()
在视图中,执行以下操作:
def upload(request):
if request.method == 'POST':
if form.is_valid():
form = MyForm(request.POST, request.FILES)
file = form.cleaned_data.get('file')
...
下面是发生的情况:
当您运行self.cleaned_data[“files”]:中的文件时,您希望它在上载文件对象列表上迭代,并将每个对象传递给处理程序函数。但是
cleaned_data['files']
不是您的列表,它只是uploadedfile的一个实例。当您在文件对象上迭代时,实际上是在读取它。因此,最终传递给handler函数的不是file对象,而是它的内容(作为字节字符串)。在迭代之前,重写此部分以检查它是否为列表。如果是单个文件,请按原样传递 在html中添加enctype=“多部分/表单数据”
form@itzmeontv它已经被添加了。对不起,我可能需要写一下。我添加了有关此字段的信息。当我在视图中传输这些操作时,我遇到了相同的错误。如果form.is\u valid():,则缺少,因此清理的\u数据不可用。是的,这是真的。谢谢