2011-08-12 111 views
0

我使用django中的ModelForm在django中創建表單。所以我有一個引用位置模型的約會模型。因爲我使用的是ModelForm,所以Location字段的選擇框自動由django自己填充。我想要的是使用ModelForm根據像say狀態這樣的屬性來控制在創建表單中填充的位置類型。在django中過濾模型表單中字段的值

我不想在ModelForm中手動覆蓋位置字段本身。我想要元素由django自己處理。我只想在過濾器中掛鉤。有什麼建議麼?

+1

有一個看看http://stackoverflow.com/questions/291945/how-do-i-filter-foreignkey-choices-in-a-django-modelform –

+0

你能提供一個例子嗎?如果您的標準不是動態的,您可以在模型中使用:limit_choices_to = {'type':'a'} – programmersbook

回答

0

如果實例存在的,而不是在一個內嵌的形式,你可以做以下的模型形式:

def __init__(self,*args,**kwargs): 
    super (AppointmentForm,self).__init__(*args,**kwargs) # populates the post 
    #filter appointments based on status 
    if self.instance.pk: 
     # the location filter below is a guess. i don't know your models. 
     locations = Location.objects.filter(status_id=self.instance.status_id) 
     self.fields['location'].queryset = locations 

另一種方法是使用回調它得到棘手......