新手问题:
我需要从views.py中的方法接受表单中的参数,但这给我带来了麻烦。在 View 中,我创建了一个包含以下代码段的方法:
def scan_page(request):
myClient = request.user.get_profile().client
form = WirelessScanForm(client = myClient) # pass parameter to the form
在forms.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一直给我错误提示:
TemplateSyntaxError: Caught NameError while rendering: name 'myClient' is not defined
(此错误发生在查询中)恐怕这里会缺少一些愚蠢的东西,但是我无法真正弄清楚为什么。请帮忙,谢谢。
最佳答案
假设我已正确纠正了格式,则出现了缩进问题:prob
在__init__
之外,因此无法访问本地myClient
变量。
但是,如果将它带入方法中,它仍然将不起作用,因为还有其他两个问题:首先,仅将字段分配给变量不会在表单上设置它。其次,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
替换为您希望在选项中显示的实际字段。
关于django表格: Passing parameter from view. py表格给出错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9723465/