Hi iam new to HTMX and as well as Ajax and JQuery. here im not familiar with htmx and i have an issue with using htmx instead of ajax and Jquery.
I have an drop down menu(options as the folder names) while selecting the option the files in the folder are displays as table there is an upload option will be enabled. using the upload option you can upload files after clicking the upload button the file is uploaded into that selected folder and displays in the same state. here, I need to show the uploaded file in that display files area without uploading the page(using htmx) and without using ajax & JQuery . how can proceed with this requirement. I have attached my html,python and JS codes here with the question..
Any help would be appreciated...
script.js
// Getting name of the uploaded file
function fileInfo() {
uploadFileName = document.getElementById('file').files[0].name;
}
function getDirectories() {
let arrayOfThisRow = [];
let inputFile = document.querySelector('input[type="file"]');
let uploadBtn = document.querySelector('input[type="submit"]');
inputFile.addEventListener("change", updateBtn);
function updateBtn(e) {
let tableTr = document.querySelectorAll("table#data tr");
for (let i = 0; i < tableTr.length; i++) {
let tableData = tableTr[i];
let tableDataQuery = tableData.querySelector("td");
if (tableDataQuery) {
arrayOfThisRow.push(tableDataQuery.textContent);
}
}
console.log(arrayOfThisRow);
if (arrayOfThisRow.includes(uploadFileName)) {
uploadBtn.disabled = true;
alert("the File you trying to upload is already uploaded");
} else if (!arrayOfThisRow) {
uploadBtn.disabled = true;
} else {
uploadBtn.disabled = false;
}
}
}
let uploadForm=document.querySelector("#file-upload-form")
uploadForm.addEventListener('submit',(e)=>{
e.preventDefault();
uploadFile = document.getElementById("file").files[0];
console.log(uploadFile);
var formData = new FormData();
formData.append("file",uploadFile);
csrf_token = $('input[name="csrfmiddlewaretoken"]').val();
formData.append("csrfmiddlewaretoken", csrf_token);
$.ajax({
url: "/uploadfiles",
type: "POST",
data: formData,
success: function (response) {
alert("File uploaded")
document.getElementById("file").value=""
// refreshDirectories();
},
cache: false,
contentType: false,
processData: false,
});
});
// disables the upload button
try {
document.addEventListener('alpine:init', () => {
console.log('bank_id');
getDirectories()
});
}
catch (ex) {
console.log(ex)
}
let bankSelect = document.querySelector('.bank_dropdown');
let fileContainer = document.querySelector('.file_upload_container')
// hiding the upload part untill select the bank from the dropdown
bankSelect.addEventListener('change', (e) => {
if (e.target.value == "") {
fileContainer.style.display = "none";
}
else {
fileContainer.style.display = "block";
}
})
views.py
import os
from urllib import response
from django.shortcuts import render,redirect
from django.views.decorators.csrf import csrf_exempt
from django.http import JsonResponse
# custom imports of dir,functions
from mis_main.settings import BASE_DIR
from .functions import get_modified_time
from .forms import UploadForm
root_path=BASE_DIR
def dropdownview(request):
banks = os.listdir(root_path)
context={"banks":banks}
return render(request, "index.html", context)
def displayfilesview(request):
is_htmx_call=request.headers.get('hx-request') == 'true'
banks = os.listdir(root_path)
if is_htmx_call:
print(is_htmx_call)
files_list = []
date_list = []
print(request.method)
if request.method == 'GET':
dd_value= request.GET.get('bank_id', None)
request.session['bank_name'] = dd_value
files_path=f"{root_path}/{dd_value}"
for files in os.scandir(files_path):
if files.is_file():
files_list.append(files.name)
date_list.append(get_modified_time(files))
files_and_date_list = zip(files_list, date_list)
return render(request, "display_files.html", {"banks":banks, "files_and_date_list":files_and_date_list})
else:
print("Not an HTMX call")
os.abort(403)
@csrf_exempt
def uploadfilesview(request):
banks = os.listdir(root_path)
files_list = []
date_list = []
form = UploadForm()
if request.method == 'POST':
bank_name = request.session['bank_name']
files_path=f"{root_path}/{bank_name}/"
for files in os.scandir(files_path):
if files.is_file():
files_list.append(files.name)
date_list.append(get_modified_time(files))
# files_and_date_list = zip(files_list, date_list)
form = UploadForm(request.POST, request.FILES)
if form.is_valid():
uploadfile=request.FILES.get('file')
with open(f"{root_path}\{bank_name}\{uploadfile}",'wb+') as destination:
for chunk in uploadfile.chunks():
destination.write(chunk)
return JsonResponse({"msg":"success"}) #"files_and_date_list":files_and_date_list,
return render(request, "index.html", {"banks":banks})
urls.py
from django.urls import path
from mis_app import views
from django.views.decorators.csrf import csrf_exempt
urlpatterns = [
path("",views.dropdownview, name="dropdown"),
path("displayfiles/",views.displayfilesview, name="displayfiles"),
path("uploadfiles",csrf_exempt(views.uploadfilesview), name="uploadfiles"),
]
index.html
<div id="content">
<div class="dropdown_container">
<h2>Select a bank</h2>
<form>
<select class="bank_dropdown" id="bank_id" name="bank_id" hx-get="displayfiles" hx-target=".container_target"
hx-trigger="change from:#bank_id" required>
<option value="None" selected disabled hidden>select your bank</option>
{% for bank in banks %}
<option value="{{bank}}">{{bank}}</option>
{% endfor %}
</select>
</form>
</div>
<p>{{error}}</p>
<br>
{% include "files_list.html" %}
<hr>
{% include "upload.html" %}
</div>
{% endblock %}
upload.html
<div class="file_upload_container" style="display:none;">
<form method="post" enctype='multipart/form-data' id="file-upload-form" >
<!-- action="{% url 'uploadfiles' %}" -->
{% csrf_token %}
<input type='file' name='file' id="file" accept=".csv, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel" onchange="fileInfo()">
<input type='submit' value='Upload' disabled>
</form>
displayfiles.html
<div class="tableFixHead">
<table id="data">
<tr>{% for files,dates in files_and_date_list %}
<td>{{files}}</td>
<td>{{dates}}</td>
</tr>
{% endfor %}
</div>
<script src="static/js/script.js"></script>