2

可能重复:
如何过滤 Django ModelForm 中的 ForeignKey 选择?

假设我有一些看起来像这样的模型:

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)

如果我为 Book 模型创建一个 ModelForm,则允许用户从所有作者中进行选择,而不仅仅是他们拥有的作者。我将如何为 Book 模型创建一个 ModelForm,让用户只选择他/她拥有的作者?

4

1 回答 1

4

您可以覆盖模型表单的__init__方法并限制作者模型选择字段的查询集。

class BookForm(forms.ModelForm):

    class Meta:
        model = Book
        # exclude the owner and set it in the view
        exclude = ('owner',) 

    def __init__(self, *args, **kwargs):
        super(BookForm, self).__init__(*args, **kwargs)
        if self.instance.owner:
            self.fields['author'].queryset = Author.objects.filter(owner=self.instance.owner)

在您看来,请确保使用已经设置了所有者的实例来实例化表单。例如要添加一本书,它看起来像这样:

def add_book(request):
    book = Book(owner=request.owner)
    form = BookForm(data=request.POST or None, instance=book)
    if form.is_valid():
        book.save()
        return HttpResponseRedirect('/success-url/')
    return render(request, "my_template.html", {'form': form})
于 2012-07-07T05:49:16.560 回答