- March 2, 2008
- newforms modelchoicefield modelform
- 5 (after 5 ratings)
ModelChoiceField allows you to use filtered queries to simplify your forms. This is great for adding objects but can fall down when you edit an existing object and the original query no longer contains the referenced field (e.g. I like to use an "active" field in several objects).
The fix is simply to include an extra param: Q(pk=object_id). You have to do this in the init method to get the object_id.
A nice thing about this is that it works for ModelForms as well as custom Forms.
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
- CustomChoiceField, Selectable label field version of ModelChoiceField by mauro 8 years, 4 months ago
- Changing queryset of a ModelChoiceField by mimog 5 years ago
- Lazy options on ModelForm fields - like setting a ModelChoiceField queryset from the view by jpic 7 years, 6 months ago
- Class ModelInfo for show object info by marinho 8 years ago
- Reorder fields directly in the ModelForm by HM 8 years, 2 months ago