# This file is part of Shuup.
#
# Copyright (c) 2012-2017, Shoop Commerce Ltd. All rights reserved.
#
# This source code is licensed under the OSL-3.0 license found in the
# LICENSE file in the root directory of this source tree.
from decimal import Decimal
from numbers import Number
from django.forms import DecimalField, Field, SelectMultiple
[docs]class PercentageField(DecimalField):
MULTIPLIER = Decimal(100)
[docs] def prepare_value(self, value):
# Percentage values are 0..1 in database, so multiply by 100
if value is not None and isinstance(value, Number):
value *= self.MULTIPLIER
return super(PercentageField, self).prepare_value(value)
[docs] def to_python(self, value):
value = super(PercentageField, self).to_python(value)
if value is not None:
# We got a value, so divide it by 100 to get the 0..1 range value
value /= self.MULTIPLIER
return value
[docs]class Select2MultipleField(Field):
widget = SelectMultiple
def __init__(self, model, *args, **kwargs):
self.model = model
super(Select2MultipleField, self).__init__(*args, **kwargs)
[docs] def to_python(self, value):
value = super(Select2MultipleField, self).to_python(value)
# Here we have sometimes None which will cause errors when
# saving related fields so let's fallback to empty list
return value or []