django表格: Passing parameter from view. py表格给出错误

标签 django forms parameter-passing

新手问题:
我需要从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/

相关文章:

python - 如何使用 Django REST Swagger 记录 pk 参数(或其他路径参数)?

python - botocore.exceptions.ClientError : An error occurred (AccessDenied) when calling the PutObject operation: Access Denied

forms - Symfony 4-如何在不构建表单的情况下添加csrf token ?

php - Symfony 3 - 将表单定义为服务

python - 将 python 模块传递给函数

django - 如果我不提交 Django 迁移怎么办?

python - 我如何过滤 itertools chain() 结果?

javascript - 使用 javascript 验证 html 表单

JavaScript 参数传递

r - 在 R Shiny 中动态更改传单 map 中心