Django form: Passing parameter from view.py to forms gives an error

New question: I need to accept a parameter in the form from a method in views.py, but this caused me problems. In the view, I created a method with the following snippet:

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

and in forms.py I defined the following view:

 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 an error: TemplateSyntaxError: Caught NameError while rendering: name 'myClient' is not defined (this error occurs in the request)

I'm afraid there will be something stupid here, but I can’t understand why. Please help, thanks.

+6
source share
1 answer

Assuming I fixed the formatting correctly, you have an indentation problem: prob is outside __init__ , so it doesn't have access to the local variable myClient .

However, if you enter it inside a method, it still won’t work, as there are two other problems: firstly, simply assigning a field to a variable will not set it in the form; and secondly, the choices attribute needs a list of 2 tuples, not just a flat list. You need the following:

 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 that you want to display in the options.

+10
source

Source: https://habr.com/ru/post/910819/


All Articles