Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
954 views
in Technique[技术] by (71.8m points)

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...