我有一個包含文件字段的模型。我想限制它到PDF文件。我在模型中寫了乾淨的方法,因爲我想檢查管理員和shell級別模型的創建。但它不適用於模型清潔方法。然而形式乾淨的方法正在工作。Django:使用python-magic的模型中的文件字段驗證
class mymodel(models.Model):
myfile = models.FileField()
def clean():
mime = magic.from_buffer(self.myfile.read(), mime=True)
print mime
if not mime == 'application/pdf':
raise ValidationError('File must be a PDF document')
class myform(forms.ModelForm):
class Meta:
model = mymodel
fields = '__all__'
def clean_myfile(self):
file = self.cleaned_data.get('myfile')
mime = magic.from_buffer(file.read(), mime=True)
print mime
if not mime == 'application/pdf':
raise forms.ValidationError('File must be a PDF document')
else:
return file
如果我上傳pdf,表單清理方法中的mime正確驗證(打印'application/pdf')。但是模型清理方法不能驗證。它將mime打印爲'application/x-empty'。我在哪裏做錯了?
還有一個問題是,如果模型清理方法引發驗證錯誤,它不會在窗體中顯示爲字段錯誤,但它顯示爲非字段錯誤。爲什麼這樣 ?
不幸的是,上面的代碼將無法正常工作。 'filetype'就像''PDF文檔,版本1.3''。你需要賦值爲'filetype = magic.from_buffer(yourfile.read(),mime = True)''以獲得''application/pdf「' –