I have a model containing file field. I want to restrict it to pdf files. I have written clean method in model because I want to check for admin and shell level model creation also. But it is not working in model clean method. However form clean method is working.
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
If I upload pdf, mime in form clean method is correctly validating (printing 'application/pdf'). But model clean method is not validating. It is printing mime as 'application/x-empty'. Where am I doing wrong ?
Also one more problem is that if model clean method raise validation error, it is not shown as field error in form, but it is showing as non-field errors. Why so ?