2011-09-05 41 views
2

我使用inlineformset_factory爲客戶和會話之間的多對多關係創建字段,並使用中間人出席模型。Django - 將參數傳遞給內嵌套件

我有我的看法如下文件:

AttendanceFormset = inlineformset_factory(
    Session, 
    Attendance, 
    formset=BaseAttendanceFormSet, 
    exclude=('user'), 
    extra=1, 
    max_num=10, 
    ) 

session = Session(user=request.user) 
formset = AttendanceFormset(request.POST, instance=session) 

而且,我需要重寫表單域的一個,我添加了下面的表單集基類:

class BaseAttendanceFormSet(BaseFormSet): 

    def add_fields(self, form, index): 
     super(BaseAttendanceFormSet, self).add_fields(form, index) 
     form.fields['client'] = forms.ModelChoiceField(
       queryset=Client.objects.filter(user=2)) 

現在,表單工作正常,但我需要傳遞一個值到formset中,以便我可以過濾基於當前用戶顯示的客戶端,而不僅僅使用ID 2.

任何人都可以 幫幫我?

任何意見讚賞。

謝謝。

編輯

對於任何閱讀,這是對我工作:

def get_field_qs(field, **kwargs): 
     if field.name == 'client': 
      return forms.ModelChoiceField(queryset=Client.objects.filter(user=request.user)) 
     return field.formfield(**kwargs) 

回答

6

如何利用inlineformset_factory的formfield_callback PARAM,而不是提供一個formset?提供一個可調用的函數,返回應該在表單中使用的字段。

表單字段回調的第一個參數是字段,而** kwargs是可選參數(例如:widget)。

例如(使用request.user的過濾器,如果需要用另一個替換。

def my_view(request): 
    #some setup code here 

    def get_field_qs(field, **kwargs): 
     formfield = field.formfield(**kwargs) 
     if field.name == 'client': 
      formfield.queryset = formfield.queryset.filter(user=request.user) 
     return formfield 

    AttendanceFormset = inlineformset_factory(
     ... 
     formfield_callback=get_field_qs 
     ... 
    ) 

    formset = AttendanceFormset(request.POST, instance=session) 

爲了更好地理解它,看到的formfield_callback in Django's FormSet code使用

+0

您好,感謝您的回覆。我嘗試添加上面的內容(儘管我必須返回field.formfield(** kwargs)而不是字段),但它現在返回所有客戶端對象。我已經在django工具欄中讀取了查詢並且過濾器沒有被應用,我試圖從if語句內輸出到控制檯,所以我知道我被擊中。任何想法爲什麼它可能會忽略它?再次感謝。 – Dan

+0

你可以用第二次嘗試更新你的問題嗎?猜你還可以返回forms.ModelChoiceField(queryset = Client.objects.filter(user = request.user))如果該字段被命名爲客戶端 – mkriheli

+0

謝謝,現在工作:) – Dan