Home

Hello. My name is Noemi Millman, and Triopter is my web development agency. We handcraft beautiful, dynamic websites.

See what I can do for you.

Noemi Millman: Triopter: May, 2009 Archives

Django 1.0: Filtering object list and ForeignKey (ModelChoiceField) in Admin Site (contrib.admin)

I’m currently building a custom multi-blogging application in Django, and one of the challenges I ran into when developing the admin section was how to restrict users to seeing and editing only their own data.

Imagine the following (simplified) models:

class Blog(models.Model):
  owner = models.OneToOneField(User, primary_key=True)
  title = models.CharField(max_length=32)

class Entry(models.Model):
  blog = models.ForeignKey(Blog)
  slug = models.SlugField(max_length=255, db_index=True)
  headline = models.CharField(max_length=255)
  content = models.TextField()

If I want to show the user only their own entries in the admin object list, I can filter the list in the ModelAdmin.queryset method — simple as pie:

class EntryAdmin(admin.ModelAdmin):
  def queryset(self, request):
    qs = super(EntryAdmin,self).queryset(request)
    return qs.filter(blog__owner=request.user)

Now, say I want to also limit what blogs the user …