Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

django form: Passing parameter from view.py to forms gives out error

Newbie question: I need to accept a parameter in a form from a method in views.py but it gave me troubles. In the view I created a method with following snippet:

def scan_page(request):
    myClient = request.user.get_profile().client
    form = WirelessScanForm(client = myClient)   # pass parameter to the form

and in the forms.py I defined the following form:

class WirelessScanForm(forms.ModelForm):
    time = forms.DateTimeField(label="Schedule Time", widget=AdminSplitDateTime())

    def __init__(self,*args,**kwargs):
        myClient = kwargs.pop("client")     # client is the parameter passed from views.py
        super(WirelessScanForm, self).__init__(*args,**kwargs)
        prob = forms.ChoiceField(label="Sniffer", choices=[ x.sniffer.plug_ip for x in Sniffer.objects.filter(client = myClient) ])

But django keeps giving me error saying: TemplateSyntaxError: Caught NameError while rendering: name 'myClient' is not defined(This error happens in the query)

I'm afraid it would be something stupid missing here, but I cannot really figure out why. Please help, thanks.

like image 267
Shang Wang Avatar asked Mar 15 '12 15:03

Shang Wang


1 Answers

Assuming I've corrected your formatting properly, you have an indentation issue: prob is outside __init__, so doesn't have access to the local myClient variable.

However if you bring it inside the method, it still won't work, as there are two other issues: first, simply assigning a field to a variable won't set it on the form; and second, the choices attribute needs a list of 2-tuples, not just a flat list. What you need is this:

def __init__(self,*args,**kwargs):
    myClient = kwargs.pop("client")     # client is the parameter passed from views.py
    super(WirelessScanForm, self).__init__(*args,**kwargs)
    self.fields['prob'] = forms.ChoiceField(label="Sniffer", choices=[(x.plug_ip, x.MY_DESCRIPTIVE_FIELD) for x in Sniffer.objects.filter(client = myClient)])

Obviously replace MY_DESCRIPTIVE_FIELD with the actual field you want displayed in the choices.

like image 107
Daniel Roseman Avatar answered Oct 05 '22 03:10

Daniel Roseman