开发者

Filtering a the value of fields in a model form in django

I am using the ModelForm in django to create my form in django. So I have a appointment model which references the Location model. Because I am using ModelForm, the select box for the Location field is automatically populated by django itself. What I want is to control the type of location that is populated in the form creating using the ModelForm based upon a开发者_如何学编程ttributes like say status.

I don't want to manually override the location field itself in the ModelForm. I want the elements to be handled by django itself. I just want to hook in a filter. Any suggestions?


If you instance is existing, and not in an inline form, you can do the following in your model form:

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

Another approach is using Callbacks which gets trickier...

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜