Model.manytomanyfield.all() Gives Attributeerror: 'manytomanydescriptor' Object Has No Attribute 'all'
I'm using Django 2.0.2, Python 3.6.4 and PyCharm 2017.3.3 Models: (in models.py) class Position(models.Model): title = models.CharField(max_length=50) gang = models.Foreign
Solution 1:
Evaluating relationships are done with an instance that is an initialized instance of the class.
An instance of the Application.
application = Application.objects.first()
application.positions.all()
Change the form queryset after initialization.
classRankingForm(forms.ModelForm):
rank = forms.IntegerField(max_value=3, min_value=1)
position = forms.ModelMultipleChoiceField(queryset=Positions.objects.none())
classMeta:
model = Ranking
exclude = ['applicant']
fields = ['rank', 'position']
def__init__(self, *args, **kwargs):
super(RankingForm, self).__init__(*args, **kwargs)
self.fields['rank'].widget.attrs.update({'class': 'form-control'})
self.fields['position'].queryset = self.instance.positions.all()
Solution 2:
You can access the current instance of your model that the ModelForm
object is working with using the instance
attribute. You can then use it to create the correct queryset in __init__
:
classRankingForm(forms.ModelForm):
...
def__init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.fields['rank'].widget.attrs.update({'class': 'form-control'})
self.fields['position'].queryset = self.instance.positions.all()
Post a Comment for "Model.manytomanyfield.all() Gives Attributeerror: 'manytomanydescriptor' Object Has No Attribute 'all'"