1๐
You override the key in your context on every iteration of the loop, store the data in a list (or whatever is appropriate) and pass that list to your context after the loop
def idf(request):
switch_ports = []
all_files = os.listdir("devices/")
for i in all_files:
with open(i, 'r') as readFile:
switch_ports.append(readFile.read())
return render(request, 'idf.html', {'switch_ports': switch_ports})
Use a pre
tag to output the results as this will format the text with a monospace font and most likely look how you want. Also use read()
instead of readlines()
to get the raw txt instead of a list of lines
{% for result in switch_ports %}
<pre>{{ result }}</pre>
{% endfor %}
0๐
context.update({"switch_ports": switch_ports})
is going to replace the existing "switch_ports" with whatever the latest iteration value is at that time so your issue makes perfect sense.
My recommendation would be to use a list append and then join to achieve the desired result.
def idf(request):
context = {}
switch_ports = []
all_files = os.listdir("devices/")
for i in all_files:
with open(i, 'r') as readFile:
switch_port = readFile.readlines()
print(switch_port)
switch_ports.append(switch_port)
readFile.close()
context.update({'switch_ports': "".join(switch_ports)})
return render(request, 'idf.html', context)
If you would like your file contents to be joined/separated by something other than "", you can use a different separator as outlined in the join documentation.
- [Answered ]-Update data in a JsonField django
- [Answered ]-DRF โ Filters in ModelSerializer
- [Answered ]-How to setup PostGIS with an existing database?
- [Answered ]-Django test in-memory SQLlite โ missing tables during test run
- [Answered ]-Django: several tables for one model.