Login

Specify a manager for the Admin

Author:
kylefox
Posted:
February 15, 2008
Language:
Python
Version:
.96
Score:
6 (after 8 ratings)

This example shows how you can easily limit the objects in the admin by specifying which Manager the admin should use. I haven't seen this documented anywhere (perhaps I've missed it), but it's proven extremely useful to me.

The example here will limit objects to those that are attached to the current Site, but you can use any Manager you want (for example, a Manager that shows only published Articles).

Finally -- not that I'm suggesting this -- but you could combine this with the ThreadLocals trick to show only objects that have been created by that user.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
class Article(models.Model):
	site = models.ForeignKey(Site)
	title = models.CharField(max_length=100)
	body = models.TextField()
	pub_date = models.DateTimeField()
	
	class Admin:
		#  In this example, the Admin's object list will show *only* Articles
		#  which are related to the current Site.
		#  However, you could specify any Manager you like:
		#  manager = MyCustomManager()
		from django.contrib.sites.managers import CurrentSiteManager
		manager = CurrentSiteManager()
	

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 2 months, 2 weeks ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 2 months, 3 weeks ago
  3. Serializer factory with Django Rest Framework by julio 9 months, 2 weeks ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 10 months, 1 week ago
  5. Help text hyperlinks by sa2812 11 months ago

Comments

peterbe (on September 14, 2009):

This does not work in Django 1.1 where you don't use the Admin class but where you have ModelAdmin class registered separately.

#

Please login first before commenting.