from django import oldforms from django.db import models from django.utils.functional import curry class SelectMultipleFieldWithDefault(oldforms.SelectMultipleField): def __init__(self, default_choice=None, *args, **kwargs): self.__default_choice = default_choice super(SelectMultipleFieldWithDefault, self).__init__(*args, **kwargs) def render(self, data): if not data and self.__default_choice: data = [self.__default_choice.id] return super(SelectMultipleFieldWithDefault, self).render(data) class ManyToManyFieldWithDefault(models.ManyToManyField): def __init__(self, *args, **kwargs): if not kwargs.get('blank', False) and not kwargs.get('null', False): self.__default_choice = kwargs.get('default', None) else: self.__default_choice = None super(ManyToManyFieldWithDefault, self).__init__(*args, **kwargs) def get_manipulator_field_objs(self): if self.rel.raw_id_admin: return [oldforms.RawIdAdminField] else: choices = self.get_choices_default() return [curry(SelectMultipleFieldWithDefault, size=min(max(len(choices), 5), 15), choices=choices, default_choice=self.__default_choice)]