Reputation: 4306
i want to filter the many to many field in modelform.
class IdealBehaviour(models.Model):
cbs_role = models.ManyToManyField(CbsRole, null=True, blank=True)
cbs = models.ForeignKey('cbs.CBS', null=True, blank=True)
ideal_behaviour = models.CharField(max_length=500, null=True, blank=True)
Description = models.CharField(max_length=1000, null=True, blank=True)
created_time = models.DateTimeField(auto_now_add = True,null=True, blank=True)
class StandardWork(models.Model):
cbs_and_role = models.ManyToManyField('userdata.CbsRole', null=True, blank=True)
standard_work_number = models.BigIntegerField(null=True, blank=True)
system_name= models.CharField(max_length=500, null=True, blank=True)
system_description=models.TextField(null=True, blank=True)
ideal_behaviour = models.ManyToManyField ('userdata.IdealBehaviour', null=True, blank=True)
publish = models.BooleanField(default=False)
created_time = models.DateTimeField(auto_now_add = True,null=True, blank=True)
class TodoListForm(ModelForm): # used in manage view
class Meta:
model = StandardWork
exclude = ('publish', 'cbs_and_role', 'standard_work_number')
widgets = {
'system_description': forms.Textarea(attrs={'rows':3}),
}
i want to display the choices of ideal_behaviour for the query
cbsobject = CBS.objects.get(id=dat)
idealbehaviour = IdealBehaviour.objects.filter(cbs=cbsobject)
I want to choices for ideal_behaviour in TodoListForm as idealbehaviour only.
How can i query to display ideal-behaviour assosciated with that perticuler cbs only in modelform?
i got the solution
def __init__(self, *args, **kwargs):
super(PollForm, self).__init__(*args, **kwargs)
if self.instance:
print "printing in form"
print self.instance.id
self.fields['ideal_behaviour'].queryset = IdealBehaviour.objects.filter(cbs__exact=self.instance.id)
but i dont how to get the id for cbs. self.instance.id its giving for standardwork id. i want id for cbs. i.e cbsobject i want in form as a instance. after that its working fine.
Upvotes: 2
Views: 1349
Reputation: 4306
Got the solution.
I don't know if it is feasible or not, but I put the forms in the views file only so I can get the instance for "cbsobject".
class PollForm(forms.ModelForm): # used in manage view
class Meta:
model = StandardWork
exclude = ('cbs_and_role','publish', 'standard_work_number')
widgets = {
'system_description': forms.Textarea(attrs={'rows':3}),
}
def __init__(self, *args, **kwargs):
super(PollForm, self).__init__(*args, **kwargs)
if self.instance:
print "printing in form"
print self.instance.id
self.fields['ideal_behaviour'].queryset = IdealBehaviour.objects.filter(cbs__exact=cbsobject)
Upvotes: 4