Skip to content

Instantly share code, notes, and snippets.

@n1k0
Forked from danni/fields.py
Created March 12, 2020 17:57
Show Gist options
  • Save n1k0/3e4f0a78964e96fe32b796db2da7ade8 to your computer and use it in GitHub Desktop.
Save n1k0/3e4f0a78964e96fe32b796db2da7ade8 to your computer and use it in GitHub Desktop.

Revisions

  1. @danni danni created this gist Mar 8, 2016.
    28 changes: 28 additions & 0 deletions fields.py
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,28 @@
    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,
    '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)