2012-07-07 59 views
2

可能重複:
How do I filter ForeignKey choices in a Django ModelForm?如何使用由特定用戶所擁有的對象創建的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,讓用戶只選擇他/她擁有的作者?

+0

參見:http://stackoverflow.com/questions/291945/how-do-i-filter-foreignkey-choices-in-a- django-modelform – Rohan 2012-07-07 05:22:44

+0

我想你可能想要使用onetoone關係。一對一關係返回一個單一的對象。 – 2012-07-07 05:33:22

回答

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}) 
相關問題