fields.py
86 lines
| 2.4 KiB
| text/x-python
|
PythonLexer
neko259
|
r1757 | from django import forms | ||
neko259
|
r1764 | from django.utils.translation import ugettext_lazy as _ | ||
neko259
|
r1757 | |||
ATTRIBUTE_PLACEHOLDER = 'placeholder' | ||||
neko259
|
r1761 | ATTRIBUTE_ROWS = 'rows' | ||
URL_ROWS = 2 | ||||
neko259
|
r1764 | URL_PLACEHOLDER = _('Insert URLs on separate lines.') | ||
neko259
|
r1761 | |||
class MultipleFileInput(forms.FileInput): | ||||
""" | ||||
Input that allows to enter many files at once, utilizing the html5 "multiple" | ||||
attribute of a file input. | ||||
""" | ||||
def value_from_datadict(self, data, files, name): | ||||
if len(files) == 0: | ||||
return None | ||||
else: | ||||
return files.getlist(name) | ||||
class MultipleFileField(forms.FileField): | ||||
""" | ||||
Field that allows to enter multiple files from one input. | ||||
""" | ||||
def to_python(self, data): | ||||
if not data or len(data) == 0: | ||||
return None | ||||
for file in data: | ||||
super().to_python(file) | ||||
return data | ||||
neko259
|
r1757 | |||
class UrlFileWidget(forms.MultiWidget): | ||||
neko259
|
r1761 | """ | ||
Widget with a file input and a text input that allows to enter either a | ||||
file from a local system, or a URL from which the file would be downloaded. | ||||
""" | ||||
neko259
|
r1757 | def __init__(self, *args, **kwargs): | ||
widgets = ( | ||||
neko259
|
r1900 | MultipleFileInput(attrs={ | ||
'accept': 'file/*', | ||||
'multiple': '' | ||||
}), | ||||
neko259
|
r1761 | forms.Textarea(attrs={ | ||
neko259
|
r1764 | ATTRIBUTE_PLACEHOLDER: URL_PLACEHOLDER, | ||
neko259
|
r1761 | ATTRIBUTE_ROWS: URL_ROWS, | ||
}), | ||||
neko259
|
r1757 | ) | ||
super().__init__(widgets, *args, **kwargs) | ||||
def decompress(self, value): | ||||
return [None, None] | ||||
class UrlFileField(forms.MultiValueField): | ||||
neko259
|
r1761 | """ | ||
Field with a file input and a text input that allows to enter either a | ||||
file from a local system, or a URL from which the file would be downloaded. | ||||
""" | ||||
neko259
|
r1757 | widget = UrlFileWidget | ||
def __init__(self, *args, **kwargs): | ||||
fields = ( | ||||
neko259
|
r1761 | MultipleFileField(required=False, label=_('File')), | ||
forms.CharField(required=False, label=_('File URL')), | ||||
neko259
|
r1757 | ) | ||
super().__init__( | ||||
fields=fields, | ||||
require_all_fields=False, *args, **kwargs) | ||||
def compress(self, data_list): | ||||
neko259
|
r1762 | all_data = [] | ||
for data in data_list: | ||||
if type(data) == list: | ||||
all_data += data | ||||
neko259
|
r1763 | elif type(data) == str and len(data) > 0: | ||
file_input = data.replace('\r\n', '\n') | ||||
url_list = file_input.split('\n') | ||||
neko259
|
r1762 | all_data += url_list | ||
neko259
|
r1757 | |||
neko259
|
r1762 | return all_data | ||