You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
We added the ability to sort using drag'n'drop and select2 autocomplete that is more user friendly that the current filtering approach. We would like to contribute that feature to this awesome project.
Here is the code we use at the moment:
fromdjango.contrib.admin.widgetsimportAutocompleteSelectMultipleclassOrderedAutocomplete(AutocompleteSelectMultiple):
defoptgroups(self, name, value, attr=None):
"""Return selected options based on the ModelChoiceIterator."""# XXX: This is based on django.contrib.admin.widgets.AutocompleteMixin:default= (None, [], 0)
groups= [default]
has_selected=False# Use a list instead of a set to keep around the order returned# by SortedManyToManyFieldselected_choices= [
str(v) forvinvalueifstr(v) notinself.choices.field.empty_values
]
ifnotself.is_requiredandnotself.allow_multiple_selected:
default[1].append(self.create_option(name, '', '', False, 0))
choices= (
(obj.pk, self.choices.field.label_from_instance(obj))
forobjinself.choices.queryset.using(self.db).filter(pk__in=selected_choices)
)
choices=list(choices)
# Sort choices according to what is returned by SortedManyToManyFieldchoices.sort(key=lambdax: selected_choices.index(str(x[0])))
foroption_value, option_labelinchoices:
selected= (
str(option_value) invalueand
(has_selectedisFalseorself.allow_multiple_selected)
)
has_selected|=selectedindex=len(default[1])
subgroup=default[1]
subgroup.append(self.create_option(name, option_value, option_label, selected_choices, index))
returngroupsclassOrderedAutocompleteMixin:
defformfield_for_manytomany(self, db_field, request=None, **kwargs):
using=kwargs.get("using")
ifdb_field.nameinself.ordered_autocomplete_fields:
kwargs['widget'] =OrderedAutocomplete(
db_field.remote_field,
self.admin_site,
using=using
)
if'queryset'notinkwargs:
queryset=self.get_field_queryset(using, db_field, request)
ifquerysetisnotNone:
kwargs['queryset'] =querysetform_field=db_field.formfield(**kwargs)
returnform_fieldreturnsuper().formfield_for_manytomany(db_field, request, **kwargs)
We added the ability to sort using drag'n'drop and select2 autocomplete that is more user friendly that the current filtering approach. We would like to contribute that feature to this awesome project.
Here is the code we use at the moment:
ref: select2/select2#3004 (comment)
The text was updated successfully, but these errors were encountered: