Aleksei Khatkevich
Aleksei Khatkevich

Reputation: 2207

JS should mantain it work after page reload

I am basically complete zero in JS, so this question might be completely dumb, anyway… I have a script that shows filename in bootstrap4 file input

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

This script is in charge for showing the file name inside the input:

enter image description here

Problem is when page gets reloaded (due to the form failed validation, for example), this field would turn itself empty, that is without file name in it. Is it possible to modify this script in a way to show filename after page gets reloaded? P.S. Files are there after reloading. They are cashed by backend. file input html code is bellow {% 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>

Upvotes: 0

Views: 67

Answers (1)

chirag soni
chirag soni

Reputation: 1026

First of all you not showed the whole code, full form and backend view. As per my understanding what I can suggest you is if you want to keep the file name even after page reload. You store that in session in your view like this:

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

and in your template you can get this session variable like this to put it at the place of file name:

{{request.session.file}}

Upvotes: 1

Related Questions