2018-10-12 22:30:47 +00:00
|
|
|
import json
|
|
|
|
|
2018-04-23 05:15:33 +00:00
|
|
|
from django.forms import widgets
|
2018-10-12 22:30:47 +00:00
|
|
|
from apps.files.models import File
|
2018-04-23 05:15:33 +00:00
|
|
|
|
|
|
|
|
|
|
|
class CommaSeparatedTextInput(widgets.HiddenInput):
|
|
|
|
def format_value(self, value):
|
|
|
|
try:
|
|
|
|
value = ','.join(value)
|
|
|
|
except TypeError:
|
|
|
|
value = ''
|
|
|
|
return super().format_value(value)
|
|
|
|
|
|
|
|
def value_from_datadict(self, data, files, name):
|
|
|
|
value = super().value_from_datadict(data, files, name)
|
|
|
|
|
|
|
|
if value == '':
|
|
|
|
return None
|
|
|
|
|
|
|
|
try:
|
|
|
|
return value.split(',')
|
|
|
|
except AttributeError:
|
|
|
|
return None
|
2018-10-12 22:30:47 +00:00
|
|
|
|
|
|
|
|
|
|
|
def idToDict(id):
|
|
|
|
file = File.objects.get(pk=id)
|
|
|
|
return dict(id=id, name=file.name())
|
|
|
|
|
|
|
|
|
|
|
|
# For clarity:
|
|
|
|
# the canonical format is a list of integers (IDs of files)
|
|
|
|
# the input/display format is a string containing a JSON list of {id=x, name=y} objects
|
|
|
|
class JSONFileListWidget(widgets.HiddenInput):
|
|
|
|
|
|
|
|
def format_value(self, value):
|
|
|
|
try:
|
|
|
|
value = [ idToDict(id) for id in value ]
|
|
|
|
value = json.dumps(value)
|
|
|
|
except TypeError:
|
|
|
|
value = ''
|
|
|
|
return super().format_value(value)
|
|
|
|
|
|
|
|
def value_from_datadict(self, data, files, name):
|
|
|
|
value = super().value_from_datadict(data, files, name)
|
|
|
|
|
|
|
|
if value == '':
|
|
|
|
return None
|
|
|
|
|
|
|
|
try:
|
|
|
|
filelist = json.loads(value)
|
|
|
|
return [ file['id'] for file in filelist ]
|
|
|
|
except JSONDecodeError:
|
|
|
|
return None
|