0

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 attributes 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?

Antony Scott
  • 21,690
  • 12
  • 62
  • 94
rajan sthapit
  • 4,194
  • 10
  • 42
  • 66

1 Answers1

0

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...

shawnwall
  • 4,549
  • 1
  • 27
  • 38