summaryrefslogtreecommitdiff
path: root/django/contrib/admin/widgets.py
diff options
context:
space:
mode:
authorJohannes Maron <info@johanneshoppe.com>2021-01-12 11:37:38 +0100
committerGitHub <noreply@github.com>2021-01-12 11:37:38 +0100
commit3071660acfbdf4b5c59457c8e9dc345d5e8894c5 (patch)
tree78b95d329ff10f4e0cd1c7b4d237d78c29b0d0bb /django/contrib/admin/widgets.py
parentba3fb2e4d0aca26f6ea37d7e31488ad09043f89d (diff)
Fixed #29010, Fixed #29138 -- Added limit_choices_to and to_field support to autocomplete fields.
* Fixed #29010 -- Added limit_choices_to support to autocomplete fields. * Fixed #29138 -- Allowed autocomplete fields to target a custom to_field rather than the PK.
Diffstat (limited to 'django/contrib/admin/widgets.py')
-rw-r--r--django/contrib/admin/widgets.py17
1 files changed, 10 insertions, 7 deletions
diff --git a/django/contrib/admin/widgets.py b/django/contrib/admin/widgets.py
index 59d1004d2d..1f438daf2d 100644
--- a/django/contrib/admin/widgets.py
+++ b/django/contrib/admin/widgets.py
@@ -380,18 +380,17 @@ class AutocompleteMixin:
Renders the necessary data attributes for select2 and adds the static form
media.
"""
- url_name = '%s:%s_%s_autocomplete'
+ url_name = '%s:autocomplete'
- def __init__(self, rel, admin_site, attrs=None, choices=(), using=None):
- self.rel = rel
+ def __init__(self, field, admin_site, attrs=None, choices=(), using=None):
+ self.field = field
self.admin_site = admin_site
self.db = using
self.choices = choices
self.attrs = {} if attrs is None else attrs.copy()
def get_url(self):
- model = self.rel.model
- return reverse(self.url_name % (self.admin_site.name, model._meta.app_label, model._meta.model_name))
+ return reverse(self.url_name % self.admin_site.name)
def build_attrs(self, base_attrs, extra_attrs=None):
"""
@@ -408,6 +407,9 @@ class AutocompleteMixin:
'data-ajax--delay': 250,
'data-ajax--type': 'GET',
'data-ajax--url': self.get_url(),
+ 'data-app-label': self.field.model._meta.app_label,
+ 'data-model-name': self.field.model._meta.model_name,
+ 'data-field-name': self.field.name,
'data-theme': 'admin-autocomplete',
'data-allow-clear': json.dumps(not self.is_required),
'data-placeholder': '', # Allows clearing of the input.
@@ -426,9 +428,10 @@ class AutocompleteMixin:
}
if not self.is_required and not self.allow_multiple_selected:
default[1].append(self.create_option(name, '', '', False, 0))
+ to_field_name = getattr(self.field.remote_field, 'field_name', self.field.model._meta.pk.name)
choices = (
- (obj.pk, self.choices.field.label_from_instance(obj))
- for obj in self.choices.queryset.using(self.db).filter(pk__in=selected_choices)
+ (getattr(obj, to_field_name), self.choices.field.label_from_instance(obj))
+ for obj in self.choices.queryset.using(self.db).filter(**{'%s__in' % to_field_name: selected_choices})
)
for option_value, option_label in choices:
selected = (