我能做一个select type=“文件”吗?

2024-05-16 20:12:35 发布

您现在位置:Python中文网/ 问答频道 /正文

好的,我需要实现一个下拉列表,在这里我可以从文件夹目录中选择一些文件。我已经有了显示文件的下拉列表,但是当我进行查询时,我得到了这个错误django.utils.datastructures.MultiValueDictKeyError:'xxxxxx',我不确定是传递了整个文件还是仅仅传递了文件名。我能做点什么吗?或者我可以将一个隐藏的输入type=“file”连接到select吗?谢谢


Tags: 文件django目录文件夹列表文件名type错误
1条回答
网友
1楼 · 发布于 2024-05-16 20:12:35

您的下拉列表应该只是一个文件名列表,您可以在清理输入时将其转换为路径

class FileSelectForm(forms.Form):
    file = forms.ChoiceField(choices=list_of_files)

    def clean_file(self):
        file_name = self.cleaned_data['file']
        file_path = ...  # You'll need to convert the name to a full path here
        return open(file_path)

现在,当您的表单提交并生效后,您将在已清理的数据中为所选文件创建一个打开的文件对象

form = FileSelectForm(request.POST)
if form.is_valid():
    form.cleaned_data['file']  # This will be a file object

相关问题 更多 >