Задать вопрос

Тел: +7 965 3737 888

475

Просмотров

3

Ответов

FileField with file extension whitelist

A simple FileField with a addition file extension whitelist. Raised ValidationError("Not allowed filetype!") if a filename contains a extension witch is not in the whitelist.

Вопрос полезен? Да0/Нет0
file_4117.py(1.3Кб)
None

Ответы (3):

Ответcomputmaxer:19.02.2013
Ответ полезен? Да0/Нет0

This snippet does not account for a field that is not required, and also does not return data so it does not get cleaned correctly.

The superclass will return False for data if the file has been cleared and the field is not required.

Here's a revised clean method for this snippet:

```

def clean(self, *args, **kwargs):
    data = super(ExtFileField, self).clean(*args, **kwargs)
    if data:
        filename = data.name
        ext = os.path.splitext(filename)[1]
        ext = ext.lower()
        if ext not in self.ext_whitelist:
            raise forms.ValidationError("Filetype not allowed! Filetypes allowed: " + ', '.join(self.ext_whitelist))
    return data

```

Ответfinity:23.05.2011
Ответ полезен? Да0/Нет0

s/through/raise an AttributeError exception. :)

Couldn't figure out how to keep djangosnippets from mucking up my code, but hopefully you get the point.

Ответfinity:23.05.2011
Ответ полезен? Да0/Нет0

This will through an AttributeError if required=False. (Due to trying to access data.name when data will be None if required == False).

I rewrote it as [HTML_REMOVED] def clean(self, *args, kwargs): data = super(ExtFileField, self).clean(*args, kwargs)

    if data is None:
        if self.required:
            raise ValidationError("This file is required")
        else:
            return
    else:
        filename = data.name
        ext = os.path.splitext(filename)[1]
        ext = ext.lower()
        if ext not in self.ext_whitelist:
            file_types = ", ".join([i for i in self.ext_whitelist])
            error = "Only allowed file types are: %s" % file_types
            raise forms.ValidationError(error)

[HTML_REMOVED]

Hopefully I'm correct on this one.