问题
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.
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)
What is actually does is allowing only SWF files at the moment.
回答1:
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])
来源:https://stackoverflow.com/questions/30642404/override-django-imagefield-validation