在django中过滤模型表单中字段的值

时间:2011-08-12 08:06:50

标签: django django-models django-admin

我在django中使用ModelForm在django中创建我的表单。所以我有一个参考Location模型的约会模型。因为我正在使用ModelForm,所以“位置”字段的选择框由django自动填充。我想要的是根据诸如状态之类的属性来控制使用ModelForm创建的表单中填充的位置类型。

我不想在ModelForm中手动覆盖位置字段本身。我希望元素由django本身处理。我只想挂钩过滤器。有什么建议吗?

1 个答案:

答案 0 :(得分: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

另一种方法是使用Callbacks变得更加棘手......