保存后删除表单的文件对象,或者在表单保存前打开文件



我想要的是下面的这个

上传文件->validate->db中的存储。

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'"

现在,我有两个想法。

有没有办法从Form对象中删除model中的对象???

有没有办法在文件存储到目录之前打开它???

我的formmodel类低于

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', ])]
)

既然validators参数支持将按给定顺序执行的验证器列表,为什么不通过文件验证器按照您已经开始的方式执行呢。或者,如果您不想将其包含在模型中,您可以创建一个表单并定义一个带有验证器列表的文件字段,方法与模型中定义的方法相同。

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

最新更新