Ian Struble avatar Ian Struble committed 1b125b1

Handling lookups for multiple FKs pointing to the same model. Multiple M2M and FK fields pointing to the same model should now be supported.

Comments (0)

Files changed (4)

django/contrib/admin/widgets.py

         model = self.settings.get('parent_model', None)
         if model:
             info = (model._meta.app_label, model._meta.object_name.lower())
-            # look for the real related name incase this is used by a formset
             qs = self.settings['queryset']
-            if self.settings.get('multiple', False):
-                names = [o.name for o in model._meta.many_to_many if o.rel.to == qs.model]
-                # formsset forms are named "form-##-<name>", hence the "-%s"
-                clean_name = [n for n in names if name == n or name.endswith("-%s" % n)][0]
-            else:
-                # @@@TODO check for multiple references to same model 
-                #         as above with m2m names?
-                clean_name = qs.model._meta.module_name
+            # Look for the real related name incase this is used by a formset
+            # but fall back to the qs model's name.
+            real_name = qs.model._meta.module_name
+            from django.db import models
+            if hasattr(model, name):
+                real_name = name
+            elif name.startswith('form-'):
+                # Hunting for fieldnames that match up with a formset field
+                # -- Please show me a better way to do this.
+                if self.settings.get('multiple', False):
+                    possible_fields = [f for f in model._meta.many_to_many 
+                                       if f.rel.to == qs.model]
+                else:
+                    possible_fields = [f for f in model._meta.fields 
+                                       if type(f) is models.ForeignKey and \
+                                           f.rel.to == qs.model]
+                for f in possible_fields:
+                    if name.endswith('-%s' % f.name):
+                        real_name = f.name
+                        break
             try:
-                url = reverse('admin:%s_%s_autocomplete' % info, args=[clean_name], current_app=self.admin_site.name)
+                url = reverse('admin:%s_%s_autocomplete' % info, args=[real_name], current_app=self.admin_site.name)
             except NoReverseMatch:
-                info = (self.admin_site.root_path, model._meta.app_label, model._meta.object_name.lower(), clean_name)
+                info = (self.admin_site.root_path, model._meta.app_label, model._meta.object_name.lower(), real_name)
                 url = '%s%s/%s/autocomplete/%s/' % info
         else:
             url = '../autocomplete/%s/' % name

tests/regressiontests/admin_widgets/models.py

 
 class Album(models.Model):
     band = models.ForeignKey(Band)
+    covered_band = models.ForeignKey(Band, related_name="original_band_set",
+                                     blank=True, null=True)
     name = models.CharField(max_length=100)
     cover_art = models.FileField(upload_to='albums')
     backside_art = MyFileField(upload_to='albums_back', null=True)

tests/regressiontests/admin_widgets/tests.py

 
 
 class AutocompleteWidgetTest(DjangoTestCase):
-    def test_render(self):
+    fixtures = ["admin-widgets-users.xml"]
+    admin_root = '/widget_admin'
+
+    def setUp(self):
         band = models.Band.objects.create(name='Linkin Park')
         band.album_set.create(
             name='Hybrid Theory', cover_art=r'albums\hybrid_theory.jpg'
         )
-        album = band.album_set.all()[0]
+        self.band = band
+        self.album = band.album_set.all()[0]
 
+    def test_render(self):
+        album = self.album
+        band = self.band
         widget_settings = {
             'fields': ('name',),
             'id': 'id',
             expected,
         )
 
+    def test_changelist_formsets(self):
+        self.client.login(username="super", password="secret")
+        response = self.client.get('%s/admin_widgets/album/' % self.admin_root )
+        self.assertContains(response,
+                            '<input type="hidden" name="form-0-band" value="%s" id="id_hidden_form-0-band" />' % self.band.pk)
+        self.assertContains(response,
+                            '<input type="text" id="id_form-0-band" value="%s" />' % self.band.name)
+        self.assertContains(response,
+                            '"source": "%s/admin_widgets/album/autocomplete/band/"' % self.admin_root)
+        self.assertContains(response,
+                            '<input type="hidden" name="form-0-covered_band" value="" id="id_hidden_form-0-covered_band" />')
+        self.assertContains(response,
+                            '<input type="text" id="id_form-0-covered_band" value="" />')
+        self.assertContains(response,
+                            '"source": "%s/admin_widgets/album/autocomplete/covered_band/"' % self.admin_root)
 
 class MultipleAutocompleteWidgetTest(DjangoTestCase):
     fixtures = ["admin-widgets-users.xml"]
         band.album_set.create(
             name='Hybrid Theory', cover_art=r'albums\hybrid_theory.jpg'
         )
+        band.members.create(
+            name="Rob Bourdon"
+        )
         band2 = models.Band.objects.create(name='Johnny Cash')
         band2.album_set.create(
             name='At San Quentin'
         response = self.client.get(lookup_by_id_url % user.email)
         self.assertEqual(simplejson.loads(response.content),
                          expected)
+
+    def test_changelist_formsets(self):
+        band = self.bands[0]
+        self.client.login(username="super", password="secret")
+        response = self.client.get('%s/admin_widgets/band/?ot=asc&o=id' % self.admin_root )
+        self.assertContains(response,
+                            '<input type="hidden" name="form-0-members" value="%s" id="id_hidden_form-0-members" />' % ",".join([str(o.pk) for o in band.members.all()]))
+        self.assertContains(response,
+                            '<input type="text" id="id_form-0-members" value="" />')
+        self.assertContains(response,
+                            '"source": "%s/admin_widgets/band/autocomplete/members/"' % self.admin_root)
+        self.assertContains(response,
+                            '<input type="hidden" name="form-0-roadies" value="" id="id_hidden_form-0-roadies" />')
+        self.assertContains(response,
+                            '<input type="text" id="id_form-0-roadies" value="" />')
+        self.assertContains(response,
+                            '"source": "%s/admin_widgets/band/autocomplete/roadies/"' % self.admin_root)
         

tests/regressiontests/admin_widgets/widgetadmin.py

 
 class AlbumAdmin(admin.ModelAdmin):
     autocomplete_fields = {
-        'band': { 'fields': ('name',) }
+        'band': { 'fields': ('name',) },
+        'covered_band': { 'fields': ('name',) }
             }
+    list_display = ('name', 'band', 'covered_band',)
+    list_editable = ('name', 'band', 'covered_band',)
+
+class BandAdmin(admin.ModelAdmin):
+    autocomplete_fields = {
+        'members': { 'fields': ('name',) },
+        'roadies': { 'fields': ('name',) }
+            }
+    list_display = ('name', 'members', 'roadies',)
+    list_editable = ('name', 'members', 'roadies',)
 
 class MemberAdmin(admin.ModelAdmin):
     autocomplete_fields = {
 
 site.register(models.User)
 site.register(models.Album, AlbumAdmin)
+site.register(models.Band, BandAdmin)
 site.register(models.Car, CarAdmin)
 site.register(models.CarTire, CarTireAdmin)
 site.register(models.Event, EventAdmin)
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.