如何使用ExtFileField片段? [英] How to use the ExtFileField snippet?

查看:41
本文介绍了如何使用ExtFileField片段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于我想将文件上传限制为某些类型的音频文件,因此我发现django片段 http://djangosnippets.org/snippets/977/,将文件上传限制为扩展名白名单中的文件:

As i want to restrict the fileupload to certain types of audiofiles, i found that django snippet http://djangosnippets.org/snippets/977/, that is restricting the fileupload to files within an extension whitelist:

class ExtFileField(forms.FileField):
"""
Same as forms.FileField, but you can specify a file extension whitelist.

>>> from django.core.files.uploadedfile import SimpleUploadedFile
>>>
>>> t = ExtFileField(ext_whitelist=(".pdf", ".txt"))
>>>
>>> t.clean(SimpleUploadedFile('filename.pdf', 'Some File Content'))
>>> t.clean(SimpleUploadedFile('filename.txt', 'Some File Content'))
>>>
>>> t.clean(SimpleUploadedFile('filename.exe', 'Some File Content'))
Traceback (most recent call last):
...
ValidationError: [u'Not allowed filetype!']
"""
def __init__(self, *args, **kwargs):
    ext_whitelist = kwargs.pop("ext_whitelist")
    self.ext_whitelist = [i.lower() for i in ext_whitelist]

    super(ExtFileField, self).__init__(*args, **kwargs)

def clean(self, *args, **kwargs):
    data = super(ExtFileField, self).clean(*args, **kwargs)
    filename = data.name
    ext = os.path.splitext(filename)[1]
    ext = ext.lower()
    if ext not in self.ext_whitelist:
        raise forms.ValidationError("Not allowed filetype!")  

到目前为止,在我的表单中,我有一个标准的FileField.这样就可以上传文件,保存并完美运行.然后像这样用FileField代替

In my forms i have a standard FileField until now. That uploads the file, saves it and works perfectly well. Then i substitute the FileField with it like this

class NewItemForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
    super(NewItemForm, self).__init__(*args, **kwargs)
    self.fields['file']=ExtFileField(ext_whitelist=(".wav", ".aif", ".flac"))

class Meta:
    model = Item
    fields = ('file','name','meta1','tags')  

当尝试上传不在白名单中的任何文件时,我收到错误消息不允许的文件类型!",这很好.但是,当在白名单中上传文件时,我收到错误消息此字段不能为空.",我不明白.我只是怀疑它与我从模型表单替换文件字段的方式有关.正确的方法是什么?

when trying to upload any file not in the whitelist i get the error message "Not allowed filetype!", which is good. But when uploading a file within the whitelist i get the error message "This field cannot be blank.", which i do not understand. I just have the suspicion it has something to do with the way i replaced the filefield from the modelform. What would be the right way to do it?

推荐答案

在"clean"方法的末尾,请确保您返回数据,以使常规的clean.forms.FileField方法可以访问它.在当前的实现中(直接从代码段中获取),forms.FileField clean方法将无法获取上载的文件.

At the end of the 'clean' method, make sure you return data so that the normal clean method of forms.FileField has access to it. In the current implementation you have (which is directly from the snippet), the forms.FileField clean method will not get the uploaded file.

我还需要调整方法,因为我有不需要的字段.结果,该实现将无法尝试访问数据的name属性(因为data为None).

I also needed to adjust my method since I had fields that were not required. As a result, the implementation would fail trying to access the name property of data (since data is None).

最后,您可以使用内容类型(未在下面显示)执行相同类型的文件白名单操作,而不是检查扩展名,而是根据将传递到字段构造函数中的content_whitelist参数检查data.file.content_type(以与ext_whitelist相同的方式).

Lastly, you can do this same sort of file whitelisting with content types (not shown below), where instead of checking the extension you would check data.file.content_type against a content_whitelist param that you would pass into your field constructor (in the same fashion as ext_whitelist).

def clean(self, *args, **kwargs):
    data = super(ExtFileField, self).clean(*args, **kwargs)
    if data:
        filename = data.name
        ext = os.path.splitext(filename)[1]
        ext = ext.lower()
        if ext not in self.ext_whitelist:
            raise forms.ValidationError("Filetype '%s' not allowed for this field" % ext)
    elif not data and self.required:
        raise forms.ValidationError("Required file not found for %s" % self.label)
    return data

这篇关于如何使用ExtFileField片段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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