from django.db import models from django import forms #class IdWidget(AdminMultipleChoiceFieldWidget): class IdWidget(forms.widgets.CheckboxSelectMultiple): template_name = 'equipment/widgets/checkbox_select.html' option_template_name = 'equipment/widgets/checkbox_option.html' 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) class Media: css = { 'all': ('css/idwidget.css',) } 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): if isinstance(value, list): 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) self.validators = [] # TODO : validateurs pertinents 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)