I had CharField with
choices
in the model, but I need for this field render as CheckboxSelectMultiple
, which returns list to a form class. With TypedChoiceField
form class, which automatic assigned to Field
with choices, it's not validate. I decided to change form_class
in the field and written a new field with TypedMultipleChoiceField
form_class
, to validate list.
class MultipleTypedChoiceModelField(models.Field):
def get_internal_type(self):
return 'MultipleTypedChoiceModelField'
def formfield(self, **kwargs):
defaults = {'form_class': TypedMultipleChoiceField, }
defaults.update(kwargs)
return super(MultipleTypedChoiceModelField, self).formfield(**defaults)
But it is have no effect. If I commented out the choices in the model field, the type is MultipleTypedChoiceModelField. So I believe that the form_class is appointed in appliance with a list of choices definition.
def formfield(self, **kwargs):
if self._choices: # or self.choices:
defaults = {'form_class': TypedMultipleChoiceField, }
defaults.update(kwargs)
return super(MultipleTypedChoiceModelField, self).formfield(**defaults)
But it is have no effect too. I have not found where is the assignment of form_class
. Maybe I have better way to change this behavior? Adding an extra model with many to many relation I do not plan, because it is obviously unnecessary.
Part of the problem is that if you have something like this in your model:
myfield = models.CharField(max_length=100, choices=MY_FIELD_CHOICES)
Django is going to assume that myfield holds just one choice, nut multiple choices.
Easiest way to implement this is to just have something like this in your model:
myfield = models.CharField(max_length=100)
and then in your custom form:
myfield = forms.MultipleChoiceField(choices=MY_FIELD_CHOICES, widget=forms.CheckboxSelectMultiple())