首页 > 解决方案 > JS 应该在页面重新加载后保持它的工作

问题描述

我在 JS 中基本上是零,所以这个问题可能完全是愚蠢的,无论如何……我有一个脚本,在 bootstrap4 文件输入中显示文件名

https://getbootstrap.com/docs/4.0/components/input-group/#custom-file-input

该脚本负责在输入中显示文件名:

在此处输入图像描述

问题是当页面重新加载时(例如,由于表单验证失败),该字段将自身变为空,即其中没有文件名。是否可以修改此脚本以在页面重新加载后显示文件名?PS文件在重新加载后在那里。他们由后端兑现。文件输入 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>

标签: javascriptdjangodjango-forms

解决方案


首先,您没有显示整个代码、完整形式和后端视图。根据我的理解,如果您想在页面重新加载后保留文件名,我可以建议您。您将其存储在视图中的会话中,如下所示:

   request.session['file']=reques.FILES

在您的模板中,您可以像这样获取此会话变量,以将其放在文件名的位置:

{{request.session.file}}

推荐阅读