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

Python 保存后删除表单的文件对象或在表单保存前打开文件,python,django,Python,Django,我想要的是下面这样 上传文件->验证->存储在数据库中 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 "D

我想要的是下面这样

上传文件->验证->存储在数据库中

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'"
那么现在,我有两个想法

有没有办法从
表单
对象中删除
模型
中的对象

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

下面是我的
表格
模型
课程

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

或者从表单中删除文档字段,并通过clean_field name方法对其进行验证

class DocumentForm(forms.ModelForm):
    # ...
    def clean_document(self):
        doc = self.cleaned_data['document']
        f = doc.read()
        # do logic
        return doc

谢谢,我应该为这个模式使用验证器。但在
validate\u doc中,当我试图打开
pd.read\u csv(value.path)
时,它返回
FileNotFoundError
,因为此时还没有创建真正的文件。在创建之前是否可以在此处打开文件?@whitebear value是一个上传到内存中的文件,您不需要从path打开它。你可以简单地做value.read()。非常感谢!!!我使用
io
从内存读取
import io df=pd.read\u csv(io.BytesIO(value.read())
它工作得非常好!!!欢迎你,@whitebear!我已经编辑了我的答案,包括如何管理上传的文件。
class DocumentForm(forms.ModelForm):
    # ...
    def clean_document(self):
        doc = self.cleaned_data['document']
        f = doc.read()
        # do logic
        return doc