Code

Ticket #11882: formfield_for_docs.diff

File formfield_for_docs.diff, 1.7 KB (added by DrMeers, 4 years ago)

Updated documentation to fix buggy example code

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