kelvinrayner
kelvinrayner

Reputation: 61

Use variable inside __init__ to outside __init__

I want to use a variable inside def__init__ outside of def__init__. This is the def__init__ in my class :

class UserResponseSearchForm(forms.Form):
    def __init__(self, *args, **kwargs):
           qry = kwargs.pop('qry')
           super(UserResponseSearchForm,self).__init__(*args, **kwargs)

I want to use variable qry outside def__init__ like this :

class UserResponseSearchForm(forms.Form):
    def __init__(self, *args, **kwargs):
           qry = kwargs.pop('qry')
           super(UserResponseSearchForm,self).__init__(*args, **kwargs)
gejala_id1 = forms.ModelMultipleChoiceField(queryset=Gejala.objects.all().values_list('gejala', flat=True).distinct().filter(gejala__icontains = qry).order_by('gejala'), widget=forms.CheckboxSelectMultiple, required=False)

I use variable qry in gejala__icontains = qry like this:

filter(gejala__icontains = qry)

And it return name 'qry' is not defined. What the problem with that? And how to use the qry variable? Hope anyone can help me.

Upvotes: 1

Views: 406

Answers (1)

dirkgroten
dirkgroten

Reputation: 20702

You need to do this inside __init__:

class UserResponseSearchForm(forms.Form):
    def __init__(self, *args, **kwargs):
        qry = kwargs.pop('qry')
        super(UserResponseSearchForm,self).__init__(*args, **kwargs)
        self.fields['gejala_id1'] = forms.ModelMultipleChoiceField(queryset=Gejala.objects.filter(gejala__icontains = qry).distinct().order_by('gejala'), widget=forms.CheckboxSelectMultiple, required=False)

Note you should not do values_list('gejala', flat=True) for a ModelMultipleChoiceField, because this field expects the objects, not a flat list of strings.

Upvotes: 2

Related Questions