Ошибка многозначного ключа при / загрузке/

#django #file-upload

#django #загрузка файла

Вопрос:

мне нужна некоторая помощь с 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
  

Комментарии:

1. Привет, я внес изменения, чтобы отобразить мой HTML-файл, и я включил enctype =»multipart / form-data» однако загрузка файла работает, но не кнопка загрузки, как только я нажимаю на кнопку, она показывает ошибку MultiValueDictKeyError

2. Прошу прощения, я только что отредактировал его. забыл скопировать часть формы.

3. Вы говорите, что получаете ошибку при нажатии кнопки загрузки, но download_view не получаете доступа request.FILES . Похоже, что действие формы в отображаемом шаблоне неверно, или у вас проблема с вашими шаблонами URL.

4. Да, эта ошибка появляется только тогда, когда я нажимаю кнопку загрузки, и она указывает на инструкцию «uploaded_file = запрос. ФАЙЛЫ [‘my_file’] «, который находится в разделе «Загрузка» в views.py . Я часами пытался решить, но безрезультатно. Мой URL следующий url (r’^upload /’, views.files_upload, name=»files_upload»), url (r ‘^download /’, views.download_view, name=»download_file»),

5. Боже, спасибо тебе за твои руководства! я решил проблему, изменив ее на {% url download_file как download_file_url %} и сформируйте действие =»{{download_file_url}}»