I’ve a file upload button in Django template. When a user clicks on the Choose File option, the file selected can be loaded.
I’m trying to add an additional option where the user can load the example files stored in the backend.
When the user clicks on #1, the file example1.xlsx
has to be loaded automatically. Similarly for #2,3,4.
Code:
<div id=main class="cont right">
<h2>Submit new task</h2>
<form action="{% url 'add_file' %}" method="post" enctype="multipart/form-data">
{% csrf_token %}
<!-- <input type="text" name="filename" placeholder="Enter File Name"><br>
<input type="file" name="file"><br>-->
<table style="margin:auto; display: block; width: 350px;">
<div class="form-group">
<tr>
<td class="td_1"><label for="{{form.file_name.id_for_label}}">Job Name</label></td>
<td>
<div class="cut example-cut">
<label for="examples" class="placeholder">
Examples
<span id="example1" class="example" onclick="setExampleValue('example1.xlsx')"> #1</span>
<span id="example2" class="example" onclick="setExampleValue('example2.xlsx')"> #2</span>
<span id="example3" class="example" onclick="setExampleValue('example3.xlsx')"> #3</span>
<span id="example3" class="example" onclick="setExampleValue('example4.xlsx')"> #4</span>
</label>
</div>
{{form.file_name}}
</td>
</tr>
<tr style="padding:5px;">
<td style="padding:5px;"><label for="{{form.files.id_for_label}}">File Name</label></td>
<td onclick="myFunction()">{{form.files_data}}</td>
</tr>
</div>
</table>
<button type="submit" class="submit" onclick="checkExtension()">Submit</button>
</form>
</div>
<script>
function setExampleValue(value) {
document.getElementById("examples").value = value;
}
</script>
If #1 is clicked, I want to load example1.xlsx from the backend and display example1.xlsx
in place of text No file chosen
.
In views.py, the following is included for loading the file path. filename
is obtained and the file path is set.
def example_file(request):
filename = request.session.get('filename')
fpath = f"job_{filename}" / "example1.xlsx"
and this is included in urls.py
path('example/', example_file, name='example'),
Suggestions on how to load the file present in this file path will be really helpful.
2
Answers
You can use Ajax to dynamically load your files. You’ll need to create a view for that. Please use this documentation and adapt it to fit your needs.
How to Implement Dependent/Chained Dropdown List with Django
another easier way is to create a REST API and use React on your frontend. This will simplify the hassle around the task.
You can store the excel files in the static directory and then display a link to it on the HTML via the context or the static template tag.
If you want to load them, you can load the entries with pyexcel, add them as dictionaries to a list and then use
Model.objects.bulk_create(the_list_of_dicts)
to create them.