2012-03-15 10 views
6

初心者質問: views.pyのメソッドからフォームのパラメータを受け入れる必要がありますが、問題が発生しました。django形式:view.pyからフォームにパラメータを渡すとエラーが発生する

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) ]) 

しかし、Djangoは、私が言ってエラー与え続け:

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

とforms.pyに、私は次の形式を定義し

TemplateSyntaxError: Caught NameError while rendering: name 'myClient' is not definedは(このエラーが発生したビューでは、私は次のコードでメソッドを作成しましたクエリ内で)

私は恐ろしいことがここにあるが、私は本当に理由を理解することはできません。助けてください、ありがとう。

+0

完全なトレースバックを投稿してください。 – jpic

+0

http://stackoverflow.com/questions/6993387/django-tables-caught-nameerror-while-rendering-global-name-name-is-not-defi –

答えて

10

フォーマットを正しく修正したと仮定すると、prob__init__の外部にあるため、ローカルのmyClient変数にはアクセスできません。

しかし、あなたがメソッドの中に持っていけば、まだ動作しません。他に2つの問題があります。まず、変数にフィールドを割り当てるだけでフォームには設定されません。第2に、choices属性にはフラットリストだけでなく、2タプルのリストが必要です。何が必要このです:

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)]) 

明らか選択肢に表示したい、実際のフィールドでMY_DESCRIPTIVE_FIELDを交換してください。

関連する問題