From everything I can find, the FileField.clean() method should be executed when a file is added to a model, but the method is simply never executed.
Note that I'm referring to the models.FileField object, not forms.FileField. See: related stackoverflow question
I am looking to validate that a file saved in models.FileField is of a certain file type and below a specified size. This is using the Django Rest Framework. The clean() method is never called on save. Why not?
View:
class FileUploadCreate(generics.CreateAPIView):
serializer_class = FileUploadSerializer
def get_queryset(self):
return FileUpload.objects.filter()
def perform_create(self, serializer):
upload = self.request.data['file']
instance = serializer.save(
name='Name',
datafile=upload,
)
instance.save()
Model:
class ContentTypeRestrictedFileField(models.FileField):
def __init__(self, *args, **kwargs):
# Log that it hits here
super(ContentTypeRestrictedFileField, self).__init__(*args, **kwargs)
def clean(self, *args, **kwargs):
print("I NEVER MAKE IT HERE")
data = super(ContentTypeRestrictedFileField, self).clean(*args, **kwargs)
file = data.file
try:
content_type = file.content_type
if content_type in self.content_types:
if file._size > self.max_upload_size:
raise ValidationError('Too big')
else:
raise ValidationError('Filetype not supported.')
except AttributeError:
pass
return data
class FileUpload(BaseModel):
name = models.CharField(max_length=128, blank=True, null=True)
datafile = ContentTypeRestrictedFileField(content_types=['video/x-msvideo', 'application/pdf', 'video/mp4', 'audio/mpeg', ], max_upload_size=1024)