2021-10-05 12:25:42 +02:00
|
|
|
# validators.py
|
|
|
|
#
|
|
|
|
# validators for file uploads, etc.
|
|
|
|
|
2021-12-31 23:59:37 +01:00
|
|
|
from django.conf import settings
|
2021-10-05 12:25:42 +02:00
|
|
|
|
2022-01-01 04:21:28 +01:00
|
|
|
#TODO: can we use the builtin Django validator instead?
|
|
|
|
# see: https://docs.djangoproject.com/en/4.0/ref/validators/#fileextensionvalidator
|
2021-10-05 12:25:42 +02:00
|
|
|
def validate_file_extension(value):
|
|
|
|
import os
|
|
|
|
from django.core.exceptions import ValidationError
|
|
|
|
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.
|
2021-12-31 23:59:37 +01:00
|
|
|
|
2022-01-01 04:21:28 +01:00
|
|
|
# check if VALID_EXTENSIONS is defined in settings.py
|
2021-12-31 23:59:37 +01:00
|
|
|
# if not use defaults
|
|
|
|
|
2022-01-01 04:21:28 +01:00
|
|
|
if settings.VALID_EXTENSIONS:
|
|
|
|
valid_extensions = settings.VALID_EXTENSIONS
|
2021-12-31 23:59:37 +01:00
|
|
|
else:
|
2022-01-01 04:21:28 +01:00
|
|
|
valid_extensions = ['.txt', '.pdf', '.doc', '.docx', '.odt', '.jpg', '.png']
|
2021-12-31 23:59:37 +01:00
|
|
|
|
2022-01-01 04:21:28 +01:00
|
|
|
if not ext.lower() in valid_extensions:
|
2021-10-05 12:25:42 +02:00
|
|
|
raise ValidationError('Unsupported file extension.')
|