poulpe/equipment/fields.py

78 lines
2.3 KiB
Python
Raw Normal View History

2018-08-02 17:55:27 +02:00
from django.db import models
from django import forms
#class IdWidget(AdminMultipleChoiceFieldWidget):
class IdWidget(forms.widgets.CheckboxSelectMultiple):
2018-08-04 05:38:03 +02:00
template_name = 'equipment/widgets/checkbox_select.html'
option_template_name = 'equipment/widgets/checkbox_option.html'
2018-08-02 17:55:27 +02:00
def __init__(self, *args, **kwargs):
# nb_items = kwargs.pop('nb_items')
# kwargs['choices'] = list(range(1, nb_items+1))
super(IdWidget, self).__init__(*args, **kwargs)
2018-08-04 05:38:03 +02:00
class Media:
css = {
'all': ('css/idwidget.css',)
}
2018-08-02 17:55:27 +02:00
class IdFormField(forms.MultipleChoiceField):
#widget = IdWidget
def __init__(self, *args, **kwargs):
if 'min_value' in kwargs:
kwargs.pop('min_value')
if 'max_value' in kwargs:
kwargs.pop('max_value')
super(IdFormField, self).__init__(*args, **kwargs)
class IdField(models.BigIntegerField):
def parse_integer(self, n):
res = []
k = 1
while(n > 0):
if n & 1:
res.append(k)
n >>= 1
k += 1
return res
def from_db_value(self, value, expression, connection, context):
if value is None:
return value
return self.parse_integer(value)
def to_python(self, value):
2018-08-04 05:38:03 +02:00
if isinstance(value, list):
2018-08-02 17:55:27 +02:00
return value
if value is None:
return value
return self.parse_integer(value)
def get_prep_value(self, value):
res = 0
for b in value:
res |= 1 << (int(b)-1)
return res
def __init__(self, separator=",", *args, **kwargs):
self.separator = separator
super(IdField, self).__init__(*args, **kwargs)
2018-08-06 18:34:07 +02:00
self.validators = [] # TODO : validateurs pertinents
2018-08-02 17:55:27 +02:00
def deconstruct(self):
name, path, args, kwargs = super(IdField, self).deconstruct()
# Only include kwarg if it's not the default
if self.separator != ",":
kwargs['separator'] = self.separator
return name, path, args, kwargs
def formfield(self, **kwargs):
# This is a fairly standard way to set up some defaults
# while letting the caller override them.
defaults = {'form_class': IdFormField}
defaults.update(kwargs)
return super(IdField, self).formfield(**defaults)