python - 保存后删除表单的文件对象或保存表单前打开文件
问题描述
我想要的是下面这样
上传文件->验证->存储在数据库中。
form = DocumentForm(request.POST, request.FILES)
form.save() # real file stored in directory
#open file and validate..
df = pd.read_csv(form.document.path)
if validate(df):
pass:
else:
form.remove() # error occurs "DocumentForm object has no attribute 'remove'"
那么现在,我有两个想法。
有没有办法从对象中删除model
对象Form
???
或者
有没有办法在文件存储到目录之前打开文件???
我form
和model
班级在下面
class DocumentForm(forms.ModelForm):
description = forms.CharField(label='comment',widget=forms.TextInput(attrs={'placeholder': 'comment'}))
class Meta:
model = MyDocument
fields = {'description','document'}
class MyDocument(models.Model):
description = models.CharField(max_length=255, blank=True)
document = models.FileField(upload_to='documents'
,validators=[FileExtensionValidator(['csv', ])]
)
解决方案
为什么不像你已经开始那样通过文件验证器来做,因为验证器参数支持将按给定顺序执行的验证器列表。或者,如果您不想将其包含在模型中,您可以创建一个表单并定义一个包含验证器列表的文件字段,其方式与模型中定义的方式相同。
def validate_doc(value):
f = value.read()
# do logic
return value
class MyDocument(models.Model):
description = models.CharField(max_length=255, blank=True)
document = models.FileField(
upload_to='documents',
validators=[FileExtensionValidator(['csv', ]), validate_doc]
)
或者
class DocumentForm(forms.ModelForm):
description = forms.CharField(
label='comment',
widget=forms.TextInput(attrs={'placeholder': 'comment'})
)
document = forms.FileField(validators=[validate_doc])
class Meta:
model = MyDocument
fields = {'description', 'document'}
或从表单中删除文档字段并通过 clean_field name 方法进行验证
class DocumentForm(forms.ModelForm):
# ...
def clean_document(self):
doc = self.cleaned_data['document']
f = doc.read()
# do logic
return doc
推荐阅读
- postgresql - 如何将“created_timestamp”:1553678246 转换为日期 dd:mm:yyyy 格式
- javascript - 一些书签不在 iOS 上执行:如何调试?
- arrays - 在 Angular 中将数组转换为对象
- c# - 无法使用 C# 和 ADO.NET 添加到数据库
- c++11 - 从 decltype 中删除类成员类型部分
- angular - 在 Angular 中注入参数化依赖和手动引导
- phpstorm - 如何在提交窗口中显示未版本控制的文件
- java - 当我在 Eclipse 中构建我的 Spring Boot 应用程序时得到一个期望
- kubernetes - Kubernetes 节点不启动
- flutter - Firestore 集合组查询流未更新