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)

PLEASE NOTE: The following explanation refers to Django v1.0 and is no longer fully applicable. Since DJango 1.1 or so, the request object is passed to ModelAdmin.formfield_for_dbfield and the new ModelAdmin.formfield_for_foreignkey by default, which makes this much simpler to accomplish.

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 …