I've found some similar questions, but not quite. I'm new-'ish' to Django, and trying to create a dynamic form, also without Models. I want to read a directory, find files of a type, and then display those files in a checklist, for selection and later processing. The selection and processing I still need to work out, but for starters, I'd just like to get the checklist working. I found the checklist form here: Django form multiple choice so that's how I've based my form.
Here's what I have so far. The print statements are just for my own troubleshooting, and I keep getting 'What args?' My guess is that I'm not properly passing in the arguments, but it looks like the number of other examples I've read.
Thanks in advance, for any leads.
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())
template (for sake of completeness)
<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>
what argswhen you POST? Sounds like you should doform = SelectForm()inelsebranch and that should give you notxt_zipparameter.