filtered ModelChoiceField queries

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
class MyModelForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        super(MyModelForm, self).__init__(*args, **kwargs)
        if self.instance:
            self.fields['myfield'].queryset = \
                MyOtherModel.objects.filter(
                    Q(active=True)|Q(pk=self.instance.myfield_id))

    class Meta:
        model = MyModel

More like this

  1. Changing queryset of a ModelChoiceField by mimog 7 months, 1 week ago
  2. CustomChoiceField, Selectable label field version of ModelChoiceField by mauro 3 years, 11 months ago
  3. Lazy options on ModelForm fields - like setting a ModelChoiceField queryset from the view by jpic 3 years, 1 month ago
  4. Dictionary of choices based in models by marcoslhc 1 year, 10 months ago
  5. Ajax auto-filtered Foreign Key Field by anentropic 2 years, 3 months ago

Comments

aaronfay (on March 4, 2008):

Thanks for this Rob, I was just trying to figure this out today...

#

mihasya (on September 19, 2010):

Much cleaner than the hack I was using for this. Thanks!

#

(Forgotten your password?)