Code

Ticket #8648: to_field.diff

File to_field.diff, 1.5 KB (added by kmtracey, 6 years ago)
Line 
1Index: django/contrib/admin/widgets.py
2===================================================================
3--- django/contrib/admin/widgets.py     (revision 8666)
4+++ django/contrib/admin/widgets.py     (working copy)
5@@ -114,6 +114,10 @@
6             (related_url, url, name))
7         output.append('<img src="%simg/admin/selector-search.gif" width="16" height="16" alt="Lookup" /></a>' % settings.ADMIN_MEDIA_PREFIX)
8         if value:
9+            # if to_field for this relation is not the primary key field, transform value to
10+            # target's pk value so selected choice is correct in the widget display
11+            if hasattr(self.rel, 'field_name') and self.rel.field_name != self.rel.to._meta.pk.attname:
12+                value = self.rel.to._default_manager.get(**{self.rel.field_name: value}).pk
13             output.append(self.label_for_value(value))
14         return mark_safe(u''.join(output))
15     
16@@ -184,6 +188,10 @@
17 
18     def render(self, name, value, *args, **kwargs):
19         rel_to = self.rel.to
20+        # if to_field for this relation is not the primary key field, transform value to
21+        # target's pk value so selected choice is correct in the widget display
22+        if value and self.rel.field_name != rel_to._meta.pk.attname:
23+            value = rel_to._default_manager.get(**{self.rel.field_name: value}).pk
24         related_url = '../../../%s/%s/' % (rel_to._meta.app_label, rel_to._meta.object_name.lower())
25         self.widget.choices = self.choices
26         output = [self.widget.render(name, value, *args, **kwargs)]