如何使用特定用户拥有的对象创建ModelForm

时间:2012-07-07 05:03:28

标签: python django django-models django-forms

  

可能重复:
  How do I filter ForeignKey choices in a Django ModelForm?

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

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,让用户只选择他/她拥有的作者?

1 个答案:

答案 0 :(得分:3)

您可以覆盖模型表单的__init__方法,并限制作者model choice field的查询集。

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})