2016-03-28 268 views
0

我发现了一些类似的问题,但并不完全。我对Django是'新'的,并且尝试创建一个动态表单,也没有Models。我想要读取一个目录,找到某个类型的文件,然后将这些文件显示在清单中,供选择和稍后处理。我仍然需要制定选择和处理方法,但对于初学者,我只想让清单工作。我在这里找到了清单表格:Django form multiple choice,这就是我的表格。将对象传递给Django表单

这是我到目前为止。打印声明仅用于我自己的疑难解答,并且我始终得到'什么参数?'我的猜测是我没有正确传递参数,但它看起来像我读过的其他示例的数量。

在此先感谢您的支持。

views.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)) 

forms.py

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

模板(为完整起见)

<div class="container"> 
    <h2>Select files for reports</h2> 
    <br/> 
    <form method='post'>{% csrf_token %} 
     {{ form.as_p }} 
     <br/> 
     <input type='submit' value='Select files' class="btn btn-primary"> 
    </form> 
</div> 
+0

你确定你在POST时不断收到'args'吗?听起来像你应该在'else'分支中执行'form = SelectForm()',并且应该没有'txt_zip'参数。 –

回答

1

你有很多错误,我很惊讶这完全在运行,因为self.txt没有在你选择CHOICES时引用它的课程级别上定义。

你得到args错误的原因是,当它不是POST时,确实没有将任何东西传递给窗体;也就是说,当你第一次访问该页面来查看空白表单时。实际上,它比这更糟,因为你根本没有实例化它;您需要使用else块中的调用括号。

一旦你解决了这个问题,你将会遇到上面提到的范围错误。您还需要在__init__方法中设置选项;您可以在该字段中定义一个空的默认值并覆盖它。因此:

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

您可能还会考虑将txt_list的计算移动到__init__的形式;这样你根本不需要通过它。

+0

非常感谢,谢谢你的解释。下一步,收集起来并处理。再次感谢! – LOlliffe