Python 将对象传递给Django窗体

Python 将对象传递给Django窗体,python,django,forms,Python,Django,Forms,我发现了一些类似的问题,但不完全如此。我是Django的新手,尝试创建一个动态表单,也没有模型。我想读一个目录,找到一种类型的文件,然后在清单中显示这些文件,供选择和以后处理。我仍然需要完成选择和处理工作,但对于初学者来说,我只想让清单发挥作用。我在这里找到了清单表格:这就是我如何建立表格的基础 这是我到目前为止所拥有的。print语句只用于我自己的故障排除,我一直得到“What args?”我的猜测是我没有正确地传递参数,但看起来像是我读过的其他示例的数量 提前感谢您提供的任何线索 视图.py

我发现了一些类似的问题,但不完全如此。我是Django的新手,尝试创建一个动态表单,也没有模型。我想读一个目录,找到一种类型的文件,然后在清单中显示这些文件,供选择和以后处理。我仍然需要完成选择和处理工作,但对于初学者来说,我只想让清单发挥作用。我在这里找到了清单表格:这就是我如何建立表格的基础

这是我到目前为止所拥有的。print语句只用于我自己的故障排除,我一直得到“What args?”我的猜测是我没有正确地传递参数,但看起来像是我读过的其他示例的数量

提前感谢您提供的任何线索

视图.py

def select(request):
    if request.method == 'POST':
        txt_list = [fn for fn in os.listdir('/static/data/') if re.search(r'\.txt$', fn, re.IGNORECASE)]
        txt_zip = zip(txt_list, txt_list)

        form = SelectForm(request.POST, txt_zip=txt_zip)
        if form.is_valid():
            choices = form.cleaned_data.get('choices')
            # do something with your results
    else:
        form = SelectForm

    return render_to_response('select.html', {'form': form},
                              context_instance=RequestContext(request))
class SelectForm(forms.Form):
    def __init__(self, *args, **kwargs):
        self.txt = kwargs.pop('txt_zip', None)
        super(SelectForm, self).__init__(*args, **kwargs)
        if self.txt is not None:
            print("Got args")
        else:
            print("What args?")

    CHOICES = (list(self.txt),)
    # tuple contents (<value>, <label>)

    choices = forms.MultipleChoiceField(choices=CHOICES, widget=forms.CheckboxSelectMultiple())
forms.py

def select(request):
    if request.method == 'POST':
        txt_list = [fn for fn in os.listdir('/static/data/') if re.search(r'\.txt$', fn, re.IGNORECASE)]
        txt_zip = zip(txt_list, txt_list)

        form = SelectForm(request.POST, txt_zip=txt_zip)
        if form.is_valid():
            choices = form.cleaned_data.get('choices')
            # do something with your results
    else:
        form = SelectForm

    return render_to_response('select.html', {'form': form},
                              context_instance=RequestContext(request))
class SelectForm(forms.Form):
    def __init__(self, *args, **kwargs):
        self.txt = kwargs.pop('txt_zip', None)
        super(SelectForm, self).__init__(*args, **kwargs)
        if self.txt is not None:
            print("Got args")
        else:
            print("What args?")

    CHOICES = (list(self.txt),)
    # tuple contents (<value>, <label>)

    choices = forms.MultipleChoiceField(choices=CHOICES, widget=forms.CheckboxSelectMultiple())
class选择表单(forms.Form):
定义初始化(self,*args,**kwargs):
self.txt=kwargs.pop('txt_-zip',无)
super(SelectForm,self)。\uuuuu init\uuuuu(*args,**kwargs)
如果self.txt不是None:
打印(“获取参数”)
其他:
打印(“什么参数?”)
选项=(列表(self.txt),)
#元组内容(,)
choices=forms.multiplechicefield(choices=choices,widget=forms.CheckboxSelectMultiple())
模板(为完整起见)


为报告选择文件

{%csrf_令牌%} {{form.as_p}}

您有很多错误,我很惊讶这会运行,因为
self.txt
没有在您在选项中引用它的类级别上定义

您得到args错误的原因是,当表单不是POST时,您确实没有向表单传递任何内容;也就是说,当您第一次访问页面以查看空表单时。事实上,它比这更糟糕,因为你根本没有实例化它;您需要在else块中使用调用括号

一旦解决了这个问题,就会出现我上面提到的范围错误。您还需要在
\uuuu init\uuu
方法中设置选项;您可以在字段中定义一个空的默认值并覆盖它。因此:

class SelectForm(forms.Form):
    choices = forms.MultipleChoiceField(choices=(), widget=forms.CheckboxSelectMultiple())
    def __init__(self, *args, **kwargs):
        txt = kwargs.pop('txt_zip', None)
        super(SelectForm, self).__init__(*args, **kwargs)
        self.fields['choices'].choices = txt

def select(request):
    txt_list = [fn for fn in os.listdir('/static/data/') if re.search(r'\.txt$', fn, re.IGNORECASE)]
    txt_zip = zip(txt_list, txt_list)

    if request.method == 'POST':

        form = SelectForm(request.POST, txt_zip=txt_zip)
        if form.is_valid():
            choices = form.cleaned_data.get('choices')
            # do something with your results
    else:
        form = SelectForm(txt_zip=txt_zip)
    ...

您还可以考虑将TxTyLIST的计算移动到代码< >这样你就不必把它传进去了。

你有很多错误,我很惊讶这会运行,因为
self.txt
不是在你在选项中引用它的类级别定义的

您得到args错误的原因是,当表单不是POST时,您确实没有向表单传递任何内容;也就是说,当您第一次访问页面以查看空表单时。事实上,它比这更糟糕,因为你根本没有实例化它;您需要在else块中使用调用括号

一旦解决了这个问题,就会出现我上面提到的范围错误。您还需要在
\uuuu init\uuu
方法中设置选项;您可以在字段中定义一个空的默认值并覆盖它。因此:

class SelectForm(forms.Form):
    choices = forms.MultipleChoiceField(choices=(), widget=forms.CheckboxSelectMultiple())
    def __init__(self, *args, **kwargs):
        txt = kwargs.pop('txt_zip', None)
        super(SelectForm, self).__init__(*args, **kwargs)
        self.fields['choices'].choices = txt

def select(request):
    txt_list = [fn for fn in os.listdir('/static/data/') if re.search(r'\.txt$', fn, re.IGNORECASE)]
    txt_zip = zip(txt_list, txt_list)

    if request.method == 'POST':

        form = SelectForm(request.POST, txt_zip=txt_zip)
        if form.is_valid():
            choices = form.cleaned_data.get('choices')
            # do something with your results
    else:
        form = SelectForm(txt_zip=txt_zip)
    ...

您还可以考虑将TxTyLIST的计算移动到代码< >这样你就不必把它传进去了。

你确定你在发帖时一直得到
what args
?听起来你应该在
else
分支中执行
form=SelectForm()
,这应该不会给你任何
txt\u-zip
参数。你确定你在发布时一直得到
what-args
?听起来您应该在
else
branch中执行
form=SelectForm()
,这应该不会给您任何
txt\u-zip
参数。