Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Django pass multiple variables from Views to HTML Template

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Here is my template file (device_list.html):

{% extends 'base.html' %}

{% block first_file %}
{% for result in file1 %}
    <div class="row">
        {{ result }}
    </div>
{% endfor %}
{% endblock %}

{% block second_file %}
{% for result in file2 %}
    <div class="row">
        {{ result }}
    </div>
{% endfor %}
{% endblock %}
}}

How can I show them both together?

>Solution :

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading