Home > Software engineering >  Django pass multiple variables from Views to HTML Template
Django pass multiple variables from Views to HTML Template

Time:08-24

I have a view like this:

def device_list(request):
    f1 = open('Switches.txt', 'r')
    file1 = f1.read()
    context1 = {'file1': file1}

    f2 = open('Routers.txt', 'r')
    file2= f2.read()
    context2 = {'file2': file2}
    
    return render(request, "device_list.html", context1, context2)

So, it reads 2 files do some process and then render to the HTML file.

The problem is, it only shows the context1 data in the page. context2 won't show up. If I remove context1, then it will show context2. So basically, they don't work together. Only one of them needs to be there to work.

Here is my template file (device_list.html):

{% extends 'base.html' %}

{% block first_file %}
{% for result in file1 %}
    <div >
        {{ result }}
    </div>
{% endfor %}
{% endblock %}

{% block second_file %}
{% for result in file2 %}
    <div >
        {{ result }}
    </div>
{% endfor %}
{% endblock %}
}}

How can I show them both together?

CodePudding user response:

Just put whole context into one dictionary:

def device_list(request):
    context = {}

    f1 = open('Switches.txt', 'r')
    file1 = f1.read()
    context.update({'file1': file1})

    f2 = open('Routers.txt', 'r')
    file2= f2.read()
    context.update({'file2': file2})
    
    return render(request, "device_list.html", context)
  • Related