'Passing a Django database pk id to Dash app

I have successfully embedded a Dash application into my Django app. I can display simple plots. But what I want to do, and have been unable to do by following documentation, is pass a pk id variable into the Dash app, pull relevant DB information according to that pk, and then plot it.

my urls.py:

urlpatterns = [
    url(r'^$', views.home, name='home'),
    url(r'^model/(?P<pk>\d+)/$', views.model, name='model'),

views.py:

def home(request):
    return render(request, 'home.html')


def model(request, pk):
    context = {'data' : {'pk': pk}}
    return render(request, 'model_results.html', context)

models.html template:

{%load plotly_dash%}
<body>
<div class="container">
    <!--Row with two equal columns-->

    <div class="row">

        <div class="col-lg-1 col-md-1 col-xl-1 col-sm-1">
           <div class = "card">
            <div class = "card-body">
                {%plotly_app name="tutorial_1" initial_arguments=data%}
            </div>
           </div>
        </div>
    </div>

</div>
</body>

and lastly, my dash app:

app = DjangoDash('tutorial_1')


app.layout = html.Div(children=[
    html.H1(children='Dash Tutorials'),
    dcc.Graph(
        id='example',
        figure={
            'data': [
                {'x': [1, 2, 3, 4, 5], 'y': [9, 6, 2, 1, 5], 'type': 'line', 'name': 'Boats'},
                {'x': [1, 2, 3, 4, 5], 'y': [8, 7, 2, 7, 3], 'type': 'bar', 'name': 'Cars'},
            ],
            'layout': {
                'title': 'Basic Dash Example'
            }
        }
        )
])

if __name__ == '__main__':
    app.run_server(debug=True)

It is unclear to me from other examples how I can use the Django ORM to pull the needed information by including something in the Dash app like doc_obj = model_example.objects.get(pk = pk).



Solution 1:[1]

It also took me a while to understand the initial_arguments parameter when embedding a dash app into an .html

First of all, since you're passing context = {'data' : {'pk': pk}} from your view to your html, the embedded dash-plotly app understands the dictionary passed as it was named in the render call. Thus, you should write {%plotly_app name="tutorial_1" initial_arguments=context%} instead of {%plotly_app name="tutorial_1" initial_arguments=data%}.

Secondly, when embedding a dash app into an html template, the initial_arguments parameter is used to set values in objects already defined in your Dash App. In this case, I understand you want to send a pk value through your URL. In order to do that, you should have an element in your Dash App with an id='pk' and which value would be set in one of this element parametres through the initial argument. Among other solutions, you could have a Div in your dash layout where you save this value:

app.layout = html.Div([
    html.Div(id='pk', title="#")
])

And as for the context dictionary definition in your view, you should write context = {'pk' : {'title': pk}} in order to save the pk value in the title.

After that, you can use callbacks including that layout element value in order to pull relevant DB information according to that pk, and then plot it, as you desired.

Here I leave you a useful YouTube tutorial where dash callbacks are quick and easily understood rather than reading tons of documentation: https://www.youtube.com/watch?v=mTsZL-VmRVE

Hope you found this useful!!

Solution 2:[2]

You should be able to do this by defining a callback function within your DashApp so that you have access to the args and kwargs, which contain necessary context to query the ORM. From there, you should be able to query the Django ORM from within the callback, assuming you import relevant the model correctly.

Example (as provided in the documentation):

def callback_c(*args,**kwargs):
    da = kwargs['dash_app']
    return "Args are [%s] and kwargs are %s" %(",".join(args), kwargs)

django-plotly-dash: extended context: https://django-plotly-dash.readthedocs.io/en/latest/extended_callbacks.html#extended-callbacks

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 SofiaDPG
Solution 2 pygeek