Skip to content

Instantly share code, notes, and snippets.

@dzerrenner
Forked from danni/fields.py
Last active December 30, 2022 15:21
Show Gist options
  • Save dzerrenner/5e8096d0779aeb3d406d6838e7e16ea2 to your computer and use it in GitHub Desktop.
Save dzerrenner/5e8096d0779aeb3d406d6838e7e16ea2 to your computer and use it in GitHub Desktop.
Multi Choice Django Array Field with Checkbox Widget
from django import forms
from django.contrib.postgres.fields import ArrayField
class ChoiceArrayField(ArrayField):
"""
A field that allows us to store an array of choices.
Uses Django 1.9's postgres ArrayField
and a MultipleChoiceField for its formfield.
Usage:
choices = ChoiceArrayField(models.CharField(max_length=...,
choices=(...,)),
default=[...])
"""
def formfield(self, **kwargs):
defaults = {
'form_class': forms.MultipleChoiceField,
'widget': forms.widgets.CheckboxSelectMultiple,
'choices': self.base_field.choices,
}
defaults.update(kwargs)
# Skip our parent's formfield implementation completely as we don't
# care for it.
# pylint:disable=bad-super-call
return super(ArrayField, self).formfield(**defaults)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment