A validator to check that an uploaded file has one of the given extensions.
It does not check the MIME type/ any file contents.
from django import forms
from .validators import FileTypeValidator
class UploadForm(forms.Form):
csv_file = forms.FileField(label="Upload file",
validators=[FileTypeValidator(('csv', 'txt'))])
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 | from django.core.validators import ValidationError
from django.utils.deconstruct import deconstructible
from django.utils.translation import ugettext_lazy as _
@deconstructible
class FileTypeValidator(object):
"""
Validates that an uploaded file has an allowed extension.
It **does not** validate the actual file content and *should not* be
considered secure.
"""
message = _('Files of type "%(invalid_type)s" are not allowed.')
code = 'invalid_type'
def __init__(self, valid_types, message=None, code=None):
self.valid_types = valid_types
if message is not None:
self.message = message
if code is not None:
self.code = code
def __call__(self, value):
extension = value.name.split('.').pop(-1)
if not extension in self.valid_types:
raise ValidationError(self.message, code=self.code,
params={'invalid_type': extension})
def __eq__(self, other):
return (
isinstance(other, FileTypeValidator) and
self.message == other.message and
(self.code == other.code)
)
def __ne__(self, other):
return not (self == other)
|
More like this
- Template tag - list punctuation for a list of items by shapiromatron 10 months, 1 week ago
- JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 2 weeks ago
- Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
- Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
- Help text hyperlinks by sa2812 1 year, 6 months ago
Comments
Please login first before commenting.