Skip to content

Commit

Permalink
Merge pull request #26 from OpenEnergyPlatform/feature/embed_chart_on…
Browse files Browse the repository at this point in the history
…_new_page

Fix going back from embedded page
  • Loading branch information
bereba authored Aug 28, 2024
2 parents 0bb3484 + 6280b31 commit eefcb4e
Show file tree
Hide file tree
Showing 2 changed files with 75 additions and 60 deletions.
2 changes: 1 addition & 1 deletion django_comparison_dashboard/urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
app_name = "django_comparison_dashboard"

urlpatterns = [
path("dashboard/", views.get_filters, name="dashboard"),
path("dashboard/", views.DashboardView.as_view(), name="dashboard"),
path("scalars/", views.ScalarView.as_view(), name="render_data"),
path("scalars/chart/", views.ScalarView.as_view(embedded=True), name="data_chart"),
path("scenarios/", views.ScenarioSelectionView.as_view(), name="scenarios"),
Expand Down
133 changes: 74 additions & 59 deletions django_comparison_dashboard/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,12 @@
from .models import NamedFilterSettings


class FormProcessingError(Exception):
def __init__(self, response, message="Form processing failed"):
self.response = response
super().__init__(message)


class KeyValueFormPartialView(View):
prefix = ""
form = None
Expand All @@ -33,81 +39,91 @@ def post(self, request):
return HttpResponse(form.as_p())


def get_filters(request):
"""
sets up the diffrent Forms/FilterSets for the dashboard
Example for incoming request: localhost:8000/dashboard/?scenario_id=5&scenario_id=10
def get_chart_and_table_from_request(request) -> tuple:
"""Render chart and data table from request."""
selected_scenarios = request.GET.getlist("scenario_id")

Parameters
----------
request
if "parameters_id" in request.GET:
# Get form parameters from DB
parameters = models.FilterSettings.objects.get(pk=request.GET["parameters_id"])
filter_parameters = parameters.filter_set
selected_chart_type = parameters.graph_filter_set.pop("chart_type")
graph_parameters = parameters.graph_filter_set
else:
# Get form parameters from request as usual
filter_parameters = request.GET
selected_chart_type = request.GET.get("chart_type")
graph_parameters = request.GET

filter_set = DataFilterSet(selected_scenarios, filter_parameters)
if not filter_set.is_valid():
response = render(
request,
"django_comparison_dashboard/dashboard.html#filters",
context=filter_set.get_context_data(),
)
response = retarget(response, "#filters")
raise FormProcessingError(response, message="Filter set not valid.")
df = preprocessing.get_scalar_data(filter_set)

selected_chart = graphs.CHART_DATA.get(selected_chart_type)
form_class = selected_chart["form_class"]
graph_filter_set = form_class(graph_parameters, data_filter_set=filter_set)
if not graph_filter_set.is_valid():
response = render(
request,
"django_comparison_dashboard/dashboard.html#graph_options",
context=graph_filter_set.get_context_data(),
)
response = retarget(response, "#graph_options")
raise FormProcessingError(response, message="Graph filter set not valid.")
chart_function = selected_chart["chart_function"]
chart = chart_function(df, graph_filter_set).to_html()
table = df.to_html()
return chart, table

Returns
-------

class DashboardView(TemplateView):
"""
selected_scenarios = request.GET.getlist("scenario_id")
filter_setting_names = list(NamedFilterSettings.objects.values("name"))
filter_set = DataFilterSet(selected_scenarios)
graph_filter_set = graphs.CHART_DATA["bar"]["form_class"]()
chart_type_form = ChartTypeForm()
return render(
request,
"django_comparison_dashboard/dashboard.html",
context=filter_set.get_context_data()
| graph_filter_set.get_context_data()
| {"name_list": filter_setting_names, "chart_type_form": chart_type_form},
)
Initializes dashboard
Including filters and chart/table if parameters are given.
Example for incoming request: localhost:8000/dashboard/?scenario_id=5&scenario_id=10
"""

template_name = "django_comparison_dashboard/dashboard.html"

def get_context_data(self, **kwargs):
selected_scenarios = self.request.GET.getlist("scenario_id")
filter_setting_names = list(NamedFilterSettings.objects.values("name"))
filter_set = DataFilterSet(selected_scenarios)
graph_filter_set = graphs.CHART_DATA["bar"]["form_class"]()
chart_type_form = ChartTypeForm()
return (
filter_set.get_context_data()
| graph_filter_set.get_context_data()
| {"name_list": filter_setting_names, "chart_type_form": chart_type_form}
)


class ScalarView(TemplateView):
template_name = "django_comparison_dashboard/partials/plot.html"
embedded = False

def get(self, request, *args, **kwargs):
selected_scenarios = self.request.GET.getlist("scenario_id")

if "parameters_id" in request.GET:
# Get form parameters from DB
parameters = models.FilterSettings.objects.get(pk=request.GET["parameters_id"])
filter_parameters = parameters.filter_set
selected_chart_type = parameters.graph_filter_set.pop("chart_type")
graph_parameters = parameters.graph_filter_set
else:
# Get form parameters from request as usual
filter_parameters = request.GET
selected_chart_type = request.GET.get("chart_type")
graph_parameters = request.GET

filter_set = DataFilterSet(selected_scenarios, filter_parameters)
if not filter_set.is_valid():
response = render(
self.request,
"django_comparison_dashboard/dashboard.html#filters",
context=filter_set.get_context_data(),
)
return retarget(response, "#filters")
df = preprocessing.get_scalar_data(filter_set)

selected_chart = graphs.CHART_DATA.get(selected_chart_type)
form_class = selected_chart["form_class"]
graph_filter_set = form_class(graph_parameters, data_filter_set=filter_set)
if not graph_filter_set.is_valid():
response = render(
self.request,
"django_comparison_dashboard/dashboard.html#graph_options",
context=graph_filter_set.get_context_data(),
)
return retarget(response, "#graph_options")
chart_function = selected_chart["chart_function"]
chart = chart_function(df, graph_filter_set).to_html()
try:
chart, table = get_chart_and_table_from_request(request)
except FormProcessingError as e:
return e.response

# Check if chart shall be returned in embedded mode
if "parameters_id" not in request.GET:
# Store parameters in DB and change query to include "parameters_id" instead of parameter query
parameter_id = save_filters(request.GET)
else:
parameter_id = request.GET["parameters_id"]

selected_scenarios = request.GET.getlist("scenario_id")
url = (
f"{request.path}?"
f"{'&'.join(f'scenario_id={scenario_id}' for scenario_id in selected_scenarios)}"
Expand All @@ -118,9 +134,8 @@ def get(self, request, *args, **kwargs):
response = HttpResponse(chart)
response["HX-Redirect"] = url
else:
context = {"chart": chart, "table": df.to_html()}
context = {"chart": chart, "table": table}
response = render(request, self.template_name, context)
response["HX-Replace-Url"] = url
return response


Expand Down

0 comments on commit eefcb4e

Please sign in to comment.