Ticket #11882: formfield_for_docs.diff

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

Updated documentation to fix buggy example code

  • docs/ref/contrib/admin/index.txt

     
    865865        def formfield_for_foreignkey(self, db_field, request, **kwargs):
    866866            if db_field.name == "car":
    867867                kwargs["queryset"] = Car.objects.filter(owner=request.user)
    868                 return db_field.formfield(**kwargs)
    869868            return super(MyModelAdmin, self).formfield_for_foreignkey(db_field, request, **kwargs)
    870869
    871870This uses the ``HttpRequest`` instance to filter the ``Car`` foreign key field
    872 to only the cars owned by the ``User`` instance.
     871to only display the cars owned by the ``User`` instance.
    873872
     873.. method:: ModelAdmin.formfield_for_manytomany(self, db_field, request, **kwargs)
     874
     875.. versionadded:: 1.1
     876
     877Like the ``formfield_for_foreignkey`` method, the ``formfield_for_manytomany``
     878method can be overridden to change the default formfield for a many to many
     879field. For example, if an owner can own multiple cars and cars can belong
     880to multiple owners -- a many to many relationship -- you could filter the
     881``Car`` foreign key field to only display the cars owned by the ``User``::
     882
     883    class MyModelAdmin(admin.ModelAdmin):
     884        def formfield_for_manytomany(self, db_field, request, **kwargs):
     885            if db_field.name == "cars":
     886                kwargs["queryset"] = Car.objects.filter(owner=request.user)
     887            return super(MyModelAdmin, self).formfield_for_manytomany(db_field, request, **kwargs)
     888
    874889.. method:: ModelAdmin.queryset(self, request)
    875890
    876891The ``queryset`` method on a ``ModelAdmin`` returns a
Back to Top