'Creating and displaying pyvis graph from django app running sql backend

This is moreso a question about pyvis graphs, but also involves a django server running with a sqlite3 backend. One of my views needs to produce an interactive pyvis graph and display it in the clients browser. I can do this without the django app with the following code:

from pyvis.network import Network
network = Network()
network.show('map.html')

As you can see with this method, pyvis creates an html file and save it to disk first. nework.show() simply opens the file in the browser. Because I will be running this on a django webapp, I would rather create the graph's html without saving it to disk, then just return it as a string in the HttpResponse for the view. Is it possible to do this, or is there another way that is more appropriate?



Solution 1:[1]

One way to do that is to save the pyvis graph into a file within the templates directory of Django. Instead of using network.show(), use network.save_graph(path_to_templates_dir/some_pyvis_file.html) and then include that file inside the template where you want to show the results using the Django tags {% include ‘pvis_graph_file.html’ %}

views.py

from pyvis.network import Network
from django.conf import settings

network = Network()
...
network.save_graph(str(settings.BASE_DIR)+'app/templates/pvis_graph_file.html')

templates/showReport.html

{% extends 'base.html' %}
{% block body %}

Content of Report with pyVis Graphs

{% include 'pvis_graph_file.html' %}

{% endblock %}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Ricardo Alvarez