覆盖Django ImageField验证 [英] Override Django ImageField validation
问题描述
我正在尝试创建一个表格,允许用户上传任何图像文件+ SWF文件。 Django的ImageField不支持SWF,因此我需要重写它。
I am trying to create a form where users will be allowed to upload any image file + SWF files. Django's ImageField does not support SWF so I need to override it.
我要做的是检查文件是否为SWF,如果为True,则返回该文件。如果不是SWF,请调用原始方法来处理文件验证。
What I want to do is to check if the file is SWF, if True, return it. If it's not SWF, call the original method which will take care of the file validation.
但是,我不确定如何实现该方法。这是我要实现的示例,但是它不起作用:
However, I am not sure how to implement that. Here is an example of what I am trying to achieve, but it does not work:
from hexagonit import swfheader
class SwfImageField(forms.ImageField):
def to_python(self, data):
try:
swfheader.parse(data)
return data
except:
return super(SwfImageField, self).to_python(data)
实际上是在当前只允许 个SWF文件。
What is actually does is allowing only SWF files at the moment.
推荐答案
另一种可能也是最简单的解决方案是使用标准的 FileField
,带有自定义验证程序:
An alternative and possibly easiest solution is to use a standard FileField
with a custom validator:
def my_validate(value):
ext = os.path.splitext(value.name)[1] # [0] returns path filename
valid = ['.jpg', '.swf']
if ext not in valid:
raise ValidationError("Unsupported file extension.")
class MyForm(forms.Form):
file = forms.FileField(validators=[my_validate])
这篇关于覆盖Django ImageField验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!