<!DOCTYPE html>
<html>
<head>
<title>Choro's quertion about checkboxes</title>
</head>
<body>
<h1>Select files to download</h1>
<form method="POST">
{% csrf_token %}
<table>
<tr><th>File A</th><td><input type="checkbox" name="selected_file" value="a"></td></tr>
<tr><th>File B</th><td><input type="checkbox" name="selected_file" value="b"></td></tr>
<tr><th>File C</th><td><input type="checkbox" name="selected_file" value="c"></td></tr>
<tr><th>File D</th><td><input type="checkbox" name="selected_file" value="d"></td></tr>
<tr><th>File E</th><td><input type="checkbox" name="selected_file" value="e"></td></tr>
<tr><th>File F</th><td><input type="checkbox" name="selected_file" value="f"></td></tr>
<tr><th></th><td><input type="submit"></td></tr>
</table>
</form>
</body>
</html>
Now, you must watch which of the files the user selected, but you have a problem: if the user selected more than one file to download you cannot send the files directly to the user in the view as a response, instead, you must present them with a page to download the files:
def choro_checkbox_question(request):
if request.method == 'GET':
return render_to_response('testapp/choro_checkbox.html', context_instance=RequestContext(request))
elif request.method == 'POST':
selected_checkboxes = request.POST.getlist('selected_file', [])
generated_filenames = []
for selected_file in selected_checkboxes:
filename = generate_file_for(selected_file)
generated_filenames.append(filename)
return render_to_response('testapp/choro_files_download.html', {'checks': selected_checkboxes,
'files': generated_filenames})
def generate_file_for(name):
filename = os.path.join(settings.MEDIA_ROOT, name)
filename = '{}.csv'.format(filename)
with open(filename, mode='w') as f:
f.write(name)
return os.path.split(filename)[1]
-- choro_files_download.html
{% load static %}
{% get_media_prefix as MEDIA_URL %}
<!DOCTYPE html>
<html>
<head>
<title>Choro's quertion about checkboxes</title>
</head>
<body>
<h1>Select files to download</h1>
<p>{{ checks }}</p>
<p>
<ul>
{% for file in files %}
<li><a href="{{ MEDIA_URL }}{{ file }}">{{ file }}</a>
{% endfor %}
</ul>
</p>
</body>
</html>
You must correctly configure MEDIA_ROOT and MEDIA_URL in your settings, and may be use a better sub-directory schema to generate the files, but you can get the general idea.
Anyway, you still can verify if the user selected only one file and download that only file directly instead of presenting a page to download; you only present the page when the user selects more than one file to download.