Django:使用python-magic在模型中进行文件字段验证 [英] Django: file field validation in model using python-magic

查看:112
本文介绍了Django:使用python-magic在模型中进行文件字段验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含文件字段的模型.我想将其限制为pdf文件.我在模型中编写了干净方法,因为我也想检查admin和shell级别模型的创建.但是它不适用于模型清理方法.但是,表单清洁方法是可行的.

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

如果我上传pdf,则表示表格清洁方法中的mime正确地验证了(打印"application/pdf").但是模型清理方法无法验证.它正在将mime打印为"application/x-empty".我在哪里做错了?

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 ?

推荐答案

由于您使用的是表单验证,因此不必担心模型清理方法

Since you are using form validation you are not to be worry about model clean method

您已经在做正确的事情

def clean_file(self):
        yourfile = self.cleaned_data.get("your_filename_on_template", False)
        filetype = magic.from_buffer(yourfile.read())
        if not "application/pdf" in filetype:
            raise ValidationError("File is not PDF.")
        return yourfile

如果您要使用模型清理,则可以创建自己的验证器

If you want to use model clean you can make your own validator

https://stackoverflow.com/a/27916582/5518973

您正在使用服务器端python-django验证,但是javascript也是验证文件客户端的好方法.对于javascript regex验证,您可以寻找此答案

You are using server side python-django validation but javascript is also nice way for validating file client side.For javascript regex validation you can look out for this answer

https://stackoverflow.com/a/17067242/5518973

或者如果您能够使用插件,则可以使用jquery验证插件

or if you are able to use plugins you can use jquery validation plugin

https://jqueryvalidation.org/

这篇关于Django:使用python-magic在模型中进行文件字段验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆