django-helpdesk/helpdesk/validators.py

36 lines
1.2 KiB
Python
Raw Normal View History

# validators.py
#
# validators for file uploads, etc.
from django.conf import settings
2022-07-12 12:34:19 +02:00
# TODO: can we use the builtin Django validator instead?
# see:
# https://docs.djangoproject.com/en/4.0/ref/validators/#fileextensionvalidator
def validate_file_extension(value):
from django.core.exceptions import ValidationError
import os
ext = os.path.splitext(value.name)[1] # [0] returns path+filename
# TODO: we might improve this with more thorough checks of file types
# rather than just the extensions.
2022-01-01 04:21:28 +01:00
# check if VALID_EXTENSIONS is defined in settings.py
# if not use defaults
2022-04-14 23:45:19 +02:00
if hasattr(settings, 'VALID_EXTENSIONS'):
2022-01-01 04:21:28 +01:00
valid_extensions = settings.VALID_EXTENSIONS
else:
2022-07-12 12:34:19 +02:00
valid_extensions = ['.txt', '.asc', '.htm', '.html',
'.pdf', '.doc', '.docx', '.odt', '.jpg', '.png', '.eml']
2022-01-01 04:21:28 +01:00
if not ext.lower() in valid_extensions:
2022-07-12 12:34:19 +02:00
# TODO: one more check in case it is a file with no extension; we
# should always allow that?
2022-04-22 20:52:51 +02:00
if not (ext.lower() == '' or ext.lower() == '.'):
2022-07-12 12:34:19 +02:00
raise ValidationError(
'Unsupported file extension: %s.' % ext.lower())