0👍
✅
I found that “self.instance” works, which is exactly what I want:
self.fields['attribute'].queryset = self.instance.attribute.all()
👤kli
2👍
When you declare a Model with
class MyModel(models.Model):
class Meta:
something = 'foo'
or a ModelForm with
class MyModelForm(forms.ModelForm):
class Meta:
model = MyModel
there is a special metaclass that upon “reading” your class definition, among
other things, it sets/replaces the Meta
attribute as _meta
.
So in order to access the associated model in your ModelForm do:
AttributeIndexForm._meta.model
But in your particular situation where you just want to customize the queryset of
the attribute
field you should do:
class AttributeIndexForm(forms.ModelForm):
class Meta:
model = AttributeIndex
def __init__(self, *args, **kwargs):
super(AttributeIndexForm, self).__init__(*args, **kwargs)
self.fields['attribute'].queryset = Attribute.objects.filter(..condition..)
self.fields['attribute'].widget = widgets.FilteredSelectMultiple("Attributes", is_stacked=False))
Source:stackexchange.com