私はいくつかの同様の質問を見つけましたが、それほどのものはありません。私はDjangoにとっては新しい、新しいモデルで、モデルもなく動的なフォームを作成しようとしています。私は、ディレクトリを読んで、タイプのファイルを見つけて、そのファイルをチェックリストに表示して、選択と後の処理をしたいと思っています。選択と処理はまだ解決する必要がありますが、まずはチェックリストを作成したいと思います。私はチェックリストのフォームをここに見つけました:Django form multiple choiceこれは私のフォームに基づいています。オブジェクトをDjangoフォームに渡す
これまで私がこれまで持っていたことは次のとおりです。 printステートメントは私のトラブルシューティングのためのものです。私の推測では、私は引数を正しく渡していないが、私が読んだ他の例の数のように見える。
事前に感謝の意を表します。
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>
POSTのときに 'what args 'を取得してもよろしいですか? 'else'ブランチで' form = SelectForm() 'を実行する必要があり、' txt_zip'パラメータを与えないように思えます。 –