[Answered ]-Django keeps replacing content on the view

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.

๐Ÿ‘คAlexi Reveal

Leave a comment