2013-03-25 53 views
0

我有以下型號:ModelForms和ForeignKeys

class Project(models.Model): 
    name = models.CharField(max_length=50) 

class ProjectParticipation(models.Model): 
    user = models.ForeignKey(User) 
    project = models.ForeignKey(Project) 

class Receipt(models.Model): 
    project_participation = models.ForeignKey(ProjectParticipation) 

而且我有以下CreateView的:

class ReceiptCreateView(LoginRequiredMixin, CreateView): 
    form_class = ReceiptForm 
    model = Receipt 
    action = 'created' 

我現在想要一個下拉菜單,用戶可以選擇的項目,新的收據應該是。用戶應該只能看到他分配的項目。 我該怎麼做?

回答

0

簡單的回答就是創建一個model form閱讀文檔,這是根本。

你也可以看看related names,這樣你就可以在FK上得到相反的結果。

class ProjectParticipation(models.Model): 
    user = models.ForeignKey(User) 
    project = models.ForeignKey(Project, related_name='ProjectParticipation') 
0

我發現使用ModelChoiceField的解決方案:

class ProjectModelChoiceField(ModelChoiceField): 
    def label_from_instance(self, obj): 
     return obj.project 

class ReceiptForm(ModelForm): 
    def __init__(self, *args, **kwargs): 
     super(ReceiptForm, self).__init__(*args, **kwargs) 
     self.fields['project_participation'] = ProjectModelChoiceField(queryset= ProjectParticipation.objects) 
class Meta: 
    model = Receipt 

然後在CreateView的:

class ReceiptCreateView(...) 
    def get_form(self, form_class): 
     form = super(ReceiptCreateView, self).get_form(form_class) 
     form.fields['project_participation'].queryset = ProjectParticipation.objects.filter(user=self.request.user) 
     return form 

是否有過濾查詢直接在設定的ModelForm的解決方案?