文件不在 request.FILES 但在 request.POST 我正在使用 htmx 发出 post 请求

File not in request.FILES but in request.POST I'm using htmx to make post request

我有一些输入片段,当满足条件时,我会在 html 页面上呈现这些输入片段,除了带有类型文件的输入外,一切正常,我想在发生更改时上传文件,但是文件对象不在 request.FILES 中,它在 request.POST 中,现在我不介意它是 request.POST 但文件显示为 'multiple': ['[object File]']

我的部分模板

<div class="my-2">
    <div id="uploaded"></div>
    <p class="lead">{{question.prompt}}</p>
    <input name="multiple" type="file" accept="image/*, .pdf" id="image_{{question.id}}"
        {% if question.required %}required{% endif %} {% if question.disabled %}disabled{% endif %} class="form-control"
        placeholder="{{question.placeholder}}" hx-post="{% url 'survey:file_multiple' %}" hx-trigger="change">
    <input type="hidden" name="filemultipleId"
        value="{% if question.form_input_type == 'file-multiple' %}{{question.id}}{% endif %}">
</div>

我没有使用 django 表单渲染表单,因为它很难而且几乎不可能实现我正在寻找的动态性

request.POST QueryDict

<QueryDict: {'csrfmiddlewaretoken': ['TiLZFEWw88cqItD8MABv6lZKYDrNaVxGF4ZMDOV3sK43540z6uOcrx5uQO6iYldA', 'date': [''], 'dateId': ['20', '5'], 'multiple': ['[object File]'], 'filemultipleId': ['18'], 'fileId': ['17']}>

回溯

Internal Server Error: /file-multiple/
Traceback (most recent call last):
  File "/home/tomms/.local/share/virtualenvs/web-app-QB9eq0sY/lib/python3.9/site-packages/django/utils/datastructures.py", line 83, in __getitem__
    list_ = super().__getitem__(key)
KeyError: 'multiple'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/home/tomms/.local/share/virtualenvs/web-app-QB9eq0sY/lib/python3.9/site-packages/django/core/handlers/exception.py", line 47, in inner
    response = get_response(request)
  File "/home/tomms/.local/share/virtualenvs/web-app-QB9eq0sY/lib/python3.9/site-packages/django/core/handlers/base.py", line 181, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "/home/tomms/.local/share/virtualenvs/web-app-QB9eq0sY/lib/python3.9/site-packages/django/contrib/auth/decorators.py", line 21, in _wrapped_view
    return view_func(request, *args, **kwargs)
  File "/home/tomms/Work/web-app/survey/inputs.py", line 238, in file_multiple
    print(request.FILES['multiple'])
  File "/home/tomms/.local/share/virtualenvs/web-app-QB9eq0sY/lib/python3.9/site-packages/django/utils/datastructures.py", line 85, in __getitem__
    raise MultiValueDictKeyError(key)
django.utils.datastructures.MultiValueDictKeyError: 'multiple'

你 add/set hx-encodingmultipart/form-data 了吗?

根据文档 https://htmx.org/docs/#files

If you wish to upload files via an htmx request, you can set the hx-encoding attribute to multipart/form-data. This will use a FormData object to submit the request, which will properly include the file in the request.