Login

Class based FileTypeValidator

Author:
jmsfwk
Posted:
May 26, 2016
Language:
Python
Version:
1.7
Tags:
validation filefield
Score:
0 (after 0 ratings)

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

Comments

Please login first before commenting.