ファイルフィールドを含むモデルがあります。PDFファイルに制限したい。管理者レベルとシェルレベルのモデル作成もチェックしたいので、モデルに clean メソッドを書きました。しかし、モデルクリーンメソッドでは機能しません。ただし、フォームクリーンメソッドは機能しています。
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 in form clean メソッドが正しく検証されます (printing 'application/pdf')。しかし、モデルのクリーンメソッドは検証されていません。「application/x-empty」として MIME を出力しています。私はどこで間違っていますか?
また、もう 1 つの問題は、モデルの clean メソッドが検証エラーを発生させた場合、フォームではフィールド エラーとして表示されず、フィールド以外のエラーとして表示されることです。なんでそうなの ?