首页 > 解决方案 > 保存后删除表单的文件对象或保存表单前打开文件

问题描述

我想要的是下面这样

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

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???

或者

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

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

标签: pythondjango

解决方案


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

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

推荐阅读