在 Django 中,如何访问 forms.py 中的文件字段?
我的 Django 应用程序中的 forms.py 中有这个表单类:
class EmailForm(EmailFormWithoutAttachment):
attachment = forms.FileField()
我想通过 clean 函数访问在 forms.py 中上传的文件以验证其名称。
def clean_attachment(self):
if self.data['attachment'].name == "someFileName.txt":
raise forms.ValidationError('This file is not allowed.')
return self.data['attachment']
然而,问题是错误指出在“QueryDict”中找不到“attachment”。我将 request.FILES 绑定到提交表单。我还在我的表单上使用 enctype="multipart/form-data" 。我想知道访问 forms.py 中的 FileField 数据的正确方法是什么。
谢谢。
I have this form class in forms.py in my Django application:
class EmailForm(EmailFormWithoutAttachment):
attachment = forms.FileField()
I would like to access the file uploaded in forms.py for validation via a clean function to validate its name.
def clean_attachment(self):
if self.data['attachment'].name == "someFileName.txt":
raise forms.ValidationError('This file is not allowed.')
return self.data['attachment']
However, the problem is that an error notes that "attachment" is not found in "QueryDict." I am binding request.FILES to the submission form. I am also using enctype="multipart/form-data" on my forms. I was wondering what is the proper way to access FileField data in forms.py.
Thank you.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
使用
self.cleaned_data['attachment']
而不是self.data['attachment']
。Use
self.cleaned_data['attachment']
instead ofself.data['attachment']
.