Last active
July 28, 2019 10:33
-
-
Save miodeqqq/533d60ac7cded22cfaf7c011381d1adf to your computer and use it in GitHub Desktop.
Django view with Plotly
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<html lang="en"> | |
<head> | |
<meta charset="UTF-8"> | |
<title>Django with Plotly - example</title> | |
</head> | |
<body> | |
{% if view.generate_plot %} | |
<div style="width: 100%; height: 100%;"> | |
{{ view.generate_plot|safe }} | |
</div> | |
{% endif %} | |
{% if error %} | |
<div> | |
<h3>No data provided to build graph :(</h3> | |
</div> | |
{% endif %} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from django.conf.urls import url | |
from statistics_plot.views import PlotGraph | |
urlpatterns = [ | |
url(r'^stats/$', PlotGraph.as_view()), | |
] |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import plotly.graph_objs as go | |
import plotly.offline as opy | |
from django.utils.decorators import method_decorator | |
from django.views.decorators.cache import never_cache | |
from django.views.decorators.csrf import csrf_exempt | |
from django.views.generic import TemplateView | |
class PlotGraph(TemplateView): | |
""" | |
Generates plot. | |
""" | |
template_name = 'plot.html' | |
@never_cache | |
@method_decorator(csrf_exempt) | |
def dispatch(self, request, *args, **kwargs): | |
return super(PlotGraph, self).dispatch(request, *args, **kwargs) | |
def get_context_data(self, **kwargs): | |
return super(PlotGraph, self).get_context_data(**kwargs) | |
def generate_plot(self): | |
try: | |
# django orm logic here | |
my_dict = {} | |
bar_data = go.Bar( | |
x=my_dict.keys(), | |
y=my_dict.values(), | |
name='Some data...', | |
) | |
data = [bar_data] | |
layout = go.Layout( | |
title='My layout', | |
xaxis=dict( | |
title='X', | |
titlefont=dict( | |
family='Verdana', | |
size=18, | |
color='#7f7f7f' | |
) | |
), | |
yaxis=dict( | |
range=[-10, 500], | |
title='Y', | |
titlefont=dict( | |
family='Verdana', | |
size=18, | |
color='#7f7f7f' | |
) | |
), | |
) | |
fig = go.Figure( | |
data=data, | |
layout=layout | |
) | |
return opy.plot( | |
fig, | |
auto_open=False, | |
output_type='div', | |
show_link=True | |
) | |
except Exception as exc: | |
print(f'Error --> {exc}') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment