The model docs strongly suggest validating all filenames of uploaded
files for security reasons, so I wrote a validator that could be used
for this, but it's not pretty:
class filenameEndsWith(object):
def __init__(self, choices=[], error_message=None):
if not choices:
raise TypeError, "at least one ending must be specified"
self.choices = choices
self.error_message = error_message or "The file must be one of
these types: %s" % \
(', '.join([ "%s (%s)" % (name, end)
for end, name in choices ]))
def __call__(self, field_data, all_data):
if isinstance(field_data, str):
filename = field_data
else:
filename = field_data['filename']
for end, name in self.choices:
if filename.endswith(end):
return
raise ValidationError, self.error_message
Then you use it like this:
class Foo(Model):
FILETYPES = (
( '.doc', 'Microsoft Word' ),
( '.pdf', 'Adobe PDF' ),
( '.txt', 'Plain Text' ),
)
content = FileField(
upload_to = "foo/%Y/%m/",
validator_list = [
filenameEndsWith(choices=FILETYPES),
]
)
The ugly part of this is in the __call__() method: When uploading a
new file, field_data is a dictionary of values, and you have to check
field_data['filename']. When just editing an existing entry without
uploading a new file, field_data is a string.
It works, but is there a better way to do this?
--
This message has been scanned for memes and
dangerous content by MindScanner, and is
believed to be unclean.
--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups
"Django users" group.
To post to this group, send email to [email protected]
To unsubscribe from this group, send email to [EMAIL PROTECTED]
For more options, visit this group at
http://groups.google.com/group/django-users
-~----------~----~----~----~------~----~------~--~---