from django.db import models
from django import forms
class MultiSelectFormField(forms.MultipleChoiceField):
widget = forms.CheckboxSelectMultiple
def __init__(self, *args, **kwargs):
self.max_choices = kwargs.pop('max_choices', 0)
super(MultiSelectFormField, self).__init__(*args, **kwargs)
def clean(self, value):
if not value and self.required:
raise forms.ValidationError(self.error_messages['required'])
if value and self.max_choices and len(value) > self.max_choices:
raise forms.ValidationError('You must select a maximum of %s choice%s.'
% (apnumber(self.max_choices), pluralize(self.max_choices)))
return value
class MultiSelectField(models.Field):
__metaclass__ = models.SubfieldBase
def get_internal_type(self):
return "CharField"
def get_choices_default(self):
return self.get_choices(include_blank=False)
def _get_FIELD_display(self, field):
value = getattr(self, field.attname)
choicedict = dict(field.choices)
def formfield(self, **kwargs):
# don't call super, as that overrides default widget if it has choices
defaults = {'required': not self.blank, 'label': capfirst(self.verbose_name),
'help_text': self.help_text, 'choices':self.choices}
if self.has_default():
defaults['initial'] = self.get_default()
defaults.update(kwargs)
return MultiSelectFormField(**defaults)
def get_db_prep_value(self, value):
if isinstance(value, basestring):
return value
elif isinstance(value, list):
return ",".join(value)
def to_python(self, value):
if isinstance(value, list):
return value
return value.split(",")
def contribute_to_class(self, cls, name):
super(MultiSelectField, self).contribute_to_class(cls, name)
if self.choices:
func = lambda self, fieldname = name, choicedict = dict(self.choices):",".join([choicedict.get(value,value) for value in getattr(self,fieldname)])
setattr(cls, 'get_%s_display' % self.name, func)
Comments
Thank you for this!
#
Hi! Did you try to dumpdata using that field ? I had to change it a bit to work good with dumping and loading data:
added new method to MultiSelectField class:
and fixed this one:
Before changes the field was serializing raw data in form:
instead of just
I'm new to django, maybe it's not a bug or maybe I was doing this wrong, but the important thing is that now it works fine for me. Hope it will help someone.
Anyway, thanks for such great field! :)
#
I have had this code running on Django 1.1 but when upgrading to 1.2.1 it stops. Keep geeting that:
Value ['a', 'b', 'c'] is not a valid choice.
Any hints to why?
#
see thread - http://groups.google.com/group/django-users/browse_thread/thread/274357214a3b4dd6
#
So you don't have to read the entire thread, for Django 1.2 you need to add a simple, empty validate function:
I haven't personally tried this yet, so not sure if it's on the form field or model field.
#
To save everybody one other minor error, include this at the top:
#
chester's fix for handling
value==Noneis also required to get this to work with creating a new item via the admin interface.#
Daniel, This snippet was very useful for me! Thank you. And Davepar... you saved my day with your tip.
Just to avoid inconsistent data in DB, I put some code in the validation method to do the validation as it should.
#
This code above goes inside the model field.
#
paddelhay, you forgot to mention that :
is required.
#