Django models.FileField.clean()方法已弃用或从未命中?

时间:2017-03-01 15:07:00

标签: django django-models django-rest-framework

从我能找到的所有内容中,当文件添加到模型时,应该执行FileField.clean()方法,但该方法永远不会被执行。

请注意,我指的是models.FileField对象,而不是forms.FileField。请参阅:related stackoverflow question

我希望验证models.FileField中保存的文件是否属于特定文件类型且低于指定大小。这是使用Django Rest Framework。从不在保存时调用clean()方法。为什么不呢?

查看:

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()            

型号:

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)

1 个答案:

答案 0 :(得分:0)

is_valid()方法自动执行clean()并在django中进行验证。

例如

form = some_form(request.POST)
if form.is_valid():
    # clean() is automatically executed