Мне нужна помощь с Django, я продолжаю сталкиваться с MultiValueDictKeyError, когда нажимаю кнопку загрузки. И это показывает MultiValueDictKeyError в / upload /
'my_file', но не уверен, как решить эту проблему после нескольких попыток. Ниже приведены мои коды для моделей, просмотра и страницы шаблона. Для вашего совета, пожалуйста.
files_ul_dl.html
<form method="post" enctype="multipart/form-data">{% csrf_token %}
<input type="file" name="my_file">
<button class="btn btn-secondary" type="submit">Upload</button>
</form>
</div>
<hr>
<h4>File Type Count</h4>
<table class="table">
<thead>
<tr>
{% for file_type in file_types %}
<th scope="col">{{ file_type }}</th>
{% endfor %}
</tr>
</thead>
<tbody>
<tr>
{% for file_type_count in file_type_counts %}
<td>{{ file_type_count }}</td>
{% endfor %}
</tr>
</tbody>
</table>
<br/>
<h4>Files</h4>
<table class="table">
<thead>
<tr>
<th scope="col">#</th>
<th scope="col">file name</th>
<th scope="col">size</th>
<th scope="col">file type</th>
<th scope="col">upload date</th>
<th scope="col"></th>
</tr>
</thead>
<tbody>
{% for file in files %}
{% url 'files_upload:download_file' as download_file_url%}
<tr>
<th scope="row">{{ forloop.counter }}</th>
<td>{{ file.upload.name }}</td>
<td>{{ file.size }}</td>
<td>{{ file.file_type }}</td>
<td>{{ file.upload_datetime }}</td>
<td>
<form action="{{ download_file_url }}" method="post">
{% csrf_token %}
{{ form }}
<input type="hidden" name="path" value="{{ file.upload.name }}">
<input type="submit" class="btn btn-primary label-success" value="Download" />
</form>
</td>
</tr>
{% endfor %}
</tbody>
</table><hr>
views.py
def files_upload(request):
context = {}
if request.method == 'POST':
uploaded_file = request.FILES['my_file']
if uploaded_file.content_type not in file_content_types:
print("INVALID CONTENT TYPE")
else:
new_file = File(upload=uploaded_file, file_type=uploaded_file.content_type)
new_file.save()
print(uploaded_file.content_type)
qs = File.objects.all().order_by('-upload_datetime')
context['files'] = qs
context["file_types"] = file_content_types
file_type_counts = []
for file_type in file_content_types:
count = File.objects.filter(file_type=file_type).count()
file_type_counts.append(count)
context["file_type_counts"] = file_type_counts
return render(request, "files_ul_dl.html", context)
def download_view(request):
if request.method == 'POST':
path = request.POST.get('path')
print(path)
file_path = os.path.join(settings.MEDIA_ROOT, path)
if os.path.exists(file_path):
with open(file_path, 'rb') as fh:
response = HttpResponse(fh.read(), content_type="application/force-download")
response['Content-Disposition'] = 'inline; filename=' + os.path.basename(file_path)
return response
raise Http404