Last active
April 8, 2021 08:10
-
-
Save stephane/00e73c0002de52b1c601 to your computer and use it in GitHub Desktop.
Widget to render ArrayField in Django. Written by Brad Montgomery.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) |
Updated for Django v2.1 (Python 3)
This was a life saver! Thanks Stephane But i needed to add
from django.utils.datastructures import MultiValueDict
Thanks
@mattfield11 Thank you. Import added
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hi! Looks like in recent revisions render_options dropped the 'value' parameter. Just FYI.