Possible Duplicate:
How do I filter ForeignKey choices in a Django ModelForm?
Say I have some models that look like this:
from django.db import models
from django.contrib.auth.models import User
class Author(models.Model):
first_name = models.CharField(max_length=100)
last_name = models.CharField(max_length=100)
owner = models.ForeignKey(User)
class Book(models.Model):
title = models.CharField(max_length=100)
authors = models.ManyToManyField(Author)
owner = models.ForeignKey(User)
If I create a ModelForm for the Book model, users are allowed to select from all authors, not just the ones they own. How would I create a ModelForm for the Book model that lets the user select only authors that s/he owns?
You can override the model form’s
__init__method and restrict the queryset for the author model choice field.In your view, make sure that you instantiate the form with an instance that already has the owner set. For example to add a book, it would look something like this: