我的 JS 基本上是零,所以这个问题可能是完全愚蠢的,无论如何...... 我有一个在 bootstrap4 文件输入中显示文件名的脚本
https://getbootstrap.com/docs/4.0/components/input-group/#custom-file-input
该脚本负责显示输入中的文件名:
问题是当页面重新加载时(例如,由于表单验证失败),该字段将自身变为空,即其中没有文件名。 是否可以修改此脚本以在页面重新加载后显示文件名? 附:重新加载后文件就在那里。它们由后端兑现。 文件输入html代码如下 {% endif %}
<script>
$(document).on('change', '.custom-file-input', function (event) {
$(this).next('.custom-file-label').html(event.target.files[0].name);
})
</script>
{% if widget.is_initial %}
<a href="{{ widget.value.url }}"><img class="ml-0" src="{% thumbnail widget.value "small" %}"></a>
{% if not widget.required %}
{% endif %}
<br>
{% endif %}
<div class="input-group mb-3">
<div class="input-group-prepend">
<span class="input-group-text" id="inputGroupFileAddon01">Upload</span>
</div>
<div class="custom-file">
<input type="{{ widget.type }}" name="{{ widget.name }}" class="custom-file-input" id="inputGroupFile02" id="inputGroupFile02" aria-describedby="inputGroupFileAddon01" {% include "django/forms/widgets/attrs.html" %}>
<label class="custom-file-label " for="inputGroupFile02">{{ widget.value|default_if_none:"Choose the file" }} {{ widget.filename }}</label>
</div>
</div>
最佳答案
首先,您没有展示完整的代码、完整的表单和后端 View 。根据我的理解,如果您想在页面重新加载后保留文件名,我可以建议您。您可以将其存储在 View 中的 session 中,如下所示:
request.session['file']=reques.FILES
在您的模板中,您可以像这样获取此 session 变量,将其放在文件名的位置:
{{request.session.file}}
关于javascript - JS 应该在页面重新加载后保持其工作状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55907909/