Skip to content

Instantly share code, notes, and snippets.

@douglasmiranda
Created July 9, 2024 01:53
Show Gist options
  • Save douglasmiranda/f94ee42b3e0e5f9f15cd3bc0c2aa75a2 to your computer and use it in GitHub Desktop.
Save douglasmiranda/f94ee42b3e0e5f9f15cd3bc0c2aa75a2 to your computer and use it in GitHub Desktop.
Django (postgres) ArrayField Multiple Choices as checkboxes.
# https://gist.github.com/danni/f55c4ce19598b2b345ef
from django import forms
from django.contrib.postgres.fields import ArrayField
class MultipleChoiceArrayField(ArrayField):
def formfield(self, **kwargs):
defaults = {
"form_class": forms.MultipleChoiceField,
"choices": self.base_field.choices,
"widget": forms.CheckboxSelectMultiple,
**kwargs,
}
return super(ArrayField, self).formfield(**defaults)
def to_python(self, value):
res = super().to_python(value)
if isinstance(res, list):
value = [self.base_field.to_python(val) for val in res]
return value
from django.db import models
from .fields import MultipleChoiceArrayField
class Config(models.Model):
# https://docs.python.org/3/library/datetime.html#datetime.date.weekday
class Weekdays(models.IntegerChoices):
MONDAY = 0, "Monday"
TUESDAY = 1, "Tuesday"
WEDNESDAY = 2, "Wednesday"
THURSDAY = 3, "Thursday"
FRIDAY = 4, "Friday"
SATURDAY = 5, "Saturday"
SUNDAY = 6, "Sunday"
@classmethod
def get_default_weekdays(cls):
return [
cls.MONDAY,
cls.TUESDAY,
cls.WEDNESDAY,
cls.THURSDAY,
cls.FRIDAY,
]
valid_weekdays = MultipleChoiceArrayField(
models.PositiveSmallIntegerField("Valid week days", choices=Weekdays),
size=7,
default=Weekdays.get_default_weekdays,
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment