[Django]-Passing a Django database pk id to Dash app

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!!

-1👍

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

👤pygeek

Leave a comment