Skip to content

Instantly share code, notes, and snippets.

@stephane
Last active April 8, 2021 08:10
Show Gist options
  • Save stephane/00e73c0002de52b1c601 to your computer and use it in GitHub Desktop.
Save stephane/00e73c0002de52b1c601 to your computer and use it in GitHub Desktop.
Widget to render ArrayField in Django. Written by Brad Montgomery.
from django.utils.datastructures import MultiValueDict
class ArrayFieldSelectMultiple(forms.SelectMultiple):
"""This is a Form Widget for use with a Postgres ArrayField. It implements
a multi-select interface that can be given a set of `choices`.
You can provide a `delimiter` keyword argument to specify the delimeter used.
"""
def __init__(self, *args, **kwargs):
# Accept a `delimiter` argument, and grab it (defaulting to a comma)
self.delimiter = kwargs.pop('delimiter', ',')
super().__init__(*args, **kwargs)
def value_from_datadict(self, data, files, name):
if isinstance(data, MultiValueDict):
# Normally, we'd want a list here, which is what we get from the
# SelectMultiple superclass, but the SimpleArrayField expects to
# get a delimited string, so we're doing a little extra work.
return self.delimiter.join(data.getlist(name))
return data.get(name)
def get_context(self, name, value, attrs):
return super().get_context(name, value.split(self.delimiter), attrs)
@Marakai
Copy link

Marakai commented Nov 7, 2016

Hi! Looks like in recent revisions render_options dropped the 'value' parameter. Just FYI.

@stephane
Copy link
Author

stephane commented Oct 1, 2018

Updated for Django v2.1 (Python 3)

@mattfield11
Copy link

This was a life saver! Thanks Stephane But i needed to add

from django.utils.datastructures import MultiValueDict

Thanks

@stephane
Copy link
Author

stephane commented Apr 8, 2021

@mattfield11 Thank you. Import added

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment