diff --git a/djangomain/dash_apps/finished_apps/stations_map.py b/djangomain/dash_apps/finished_apps/stations_map.py new file mode 100644 index 00000000..4f736759 --- /dev/null +++ b/djangomain/dash_apps/finished_apps/stations_map.py @@ -0,0 +1,63 @@ +import dash_bootstrap_components as dbc +import pandas as pd +import plotly.express as px +from dash import Input, Output, dcc, html +from django.forms.models import model_to_dict +from django_plotly_dash import DjangoDash + +from station.models import Station + +# Create a Dash app +app = DjangoDash( + "StationsMap", + external_stylesheets=[dbc.themes.BOOTSTRAP], +) + + +# Create layout +app.layout = html.Div( + children=[ + html.Div(id="test_list"), + dcc.Graph( + id="map_graph", + style={"display": "none"}, + ), + html.Div(id="stations_list", style={"display": "none"}), + ] +) + + +@app.callback( + [ + Output("map_graph", "figure"), + Output("map_graph", "style"), + ], + Input("stations_list", "children"), +) +def update_map(stations) -> px.line: + station_objs = [ + model_to_dict(Station.objects.get(station_code=code)) for code in stations + ] + + keys = [ + "station_id", + "station_code", + "station_name", + "station_latitude", + "station_longitude", + ] + + stations_filtered = [{key: obj[key] for key in keys} for obj in station_objs] + + df = pd.DataFrame(stations_filtered, columns=keys) + plot = px.scatter_mapbox( + df, + lat="station_latitude", + lon="station_longitude", + hover_name="station_code", + zoom=3.6, + ) + plot.update_layout(mapbox_style="open-street-map") + plot.update_layout(margin={"r": 0, "t": 0, "l": 0, "b": 0}) + + return plot, {"display": "block"} diff --git a/djangomain/views.py b/djangomain/views.py index 736740a6..dfb1d328 100755 --- a/djangomain/views.py +++ b/djangomain/views.py @@ -1,11 +1,25 @@ +from django.shortcuts import render from django.views.generic.base import TemplateView from drf_yasg import openapi from drf_yasg.views import get_schema_view +from guardian.shortcuts import get_objects_for_user from rest_framework import permissions +from station.models import Station + class HomePageView(TemplateView): - template_name = "home.html" + """ + View for displaying the home page and map dash app. + """ + + def get(self, request, *args, **kwargs): + from .dash_apps.finished_apps import stations_map + + stations = get_objects_for_user(request.user, "view_station", klass=Station) + station_codes = list(stations.values_list("station_code", flat=True)) + context = {"django_context": {"stations_list": {"children": station_codes}}} + return render(request, "home.html", context) schema_view = get_schema_view( diff --git a/templates/home.html b/templates/home.html index a788c3ac..338dcaff 100644 --- a/templates/home.html +++ b/templates/home.html @@ -4,15 +4,18 @@ {% load rest_framework %} {% load static %} {% load django_bootstrap5 %} +{% load plotly_dash %} {% block content %}