Code

Ticket #11882: 11882.diff

File 11882.diff, 1.4 KB (added by timo, 4 years ago)

small edits to existing patch

Line 
1Index: docs/ref/contrib/admin/index.txt
2===================================================================
3--- docs/ref/contrib/admin/index.txt    (revision 11785)
4+++ docs/ref/contrib/admin/index.txt    (working copy)
5@@ -818,8 +818,25 @@
6             return super(MyModelAdmin, self).formfield_for_foreignkey(db_field, request, **kwargs)
7 
8 This uses the ``HttpRequest`` instance to filter the ``Car`` foreign key field
9-to only the cars owned by the ``User`` instance.
10+to only display the cars owned by the ``User`` instance.
11 
12+.. method:: ModelAdmin.formfield_for_manytomany(self, db_field, request, **kwargs)
13+
14+.. versionadded:: 1.1
15+
16+Like the ``formfield_for_foreignkey`` method, the ``formfield_for_manytomany``
17+method can be overridden to change the default formfield for a many to many
18+field. For example, if an owner can own multiple cars and cars can belong
19+to multiple owners -- a many to many relationship -- you could filter the
20+``Car`` foreign key field to only display the cars owned by the ``User``::
21+
22+    class MyModelAdmin(admin.ModelAdmin):
23+        def formfield_for_manytomany(self, db_field, request, **kwargs):
24+            if db_field.name == "cars":
25+                kwargs["queryset"] = Car.objects.filter(owner=request.user)
26+                return db_field.formfield(**kwargs)
27+            return super(MyModelAdmin, self).formfield_for_manytomany(db_field, request, **kwargs)
28+
29 Other methods
30 ~~~~~~~~~~~~~
31