Using Django logged-in user information in Dash App

Is possible to pass the currently logged-in user full name/group etc. into a Dash app created in Django?

An example of an app can be found here: Dash DataTable | Dash for Python Documentation | Plotly

Assume you for instance want to pass the logged in name into the data table. How can this be done?

For example, creating a variable “name” through “name = request.user.get_full_name” directly into the script or some type of similar statement does not work.

Thanks!

How are you integrating Dash with Django?

Hi, thanks for your reply.

The App looks something like this (explanation below):

import dash
import io
import spacy
import base64
from dash.dependencies import Input, Output, State
import dash_table
import dash_core_components as dcc
import dash_html_components as html
import pandas as pd
import time
from django_plotly_dash import DjangoDash
from sqlalchemy import create_engine
import psycopg2
import datetime


now = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")

#Engine for SQL
engine = create_engine('postgresql://postgres:.........@localhost:5432/data')

#SpaCy
nlp = spacy.load("home/dash_apps/finished_apps/bank_rec")

external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']
app = DjangoDash('SimpleExample', external_stylesheets=external_stylesheets)

app.layout = html.Div([
    dcc.Upload(
        id='datatable-upload',
        children=html.Div([
            'Drag and Drop or ',
            html.A('Select Files')
        ]),
        style={
            'width': '99%', 'height': '60px', 'lineHeight': '60px',
            'borderWidth': '1px', 'borderStyle': 'dashed',
            'borderRadius': '5px', 'textAlign': 'center', 'margin': '10px'
        },
    ),
    dash_table.DataTable(id='datatable-upload-container',
                         export_format='xlsx',
                         export_headers='display',
                         editable=True,
                         page_size=50,
                         style_table={'height': '500px', 'overflowY': 'auto'},
                         filter_action='native',
                         style_cell={
                             'textAlign': 'left',
                             'minWidth': 50, 'maxWidth': 50, 'width': 50,
                             'overflow': 'hidden',
                             'textOverflow': 'ellipsis',
                         },
                         style_cell_conditional=[
                             {
                                 'if': {'column_id': 'Turnover'},
                                 'textAlign': 'right'
                             }
                         ],
                         style_header={
                             'backgroundColor': 'rgb(230, 230, 230)',
                             'fontWeight': 'bold',
                         },
                        style_data_conditional=[
                                {
                                    'if': {'row_index': 'odd'},
                                    'backgroundColor': 'rgb(248, 248, 248)'
                                }
                         ],
                         )
])


def parse_contents(contents, filename):
    content_type, content_string = contents.split(',')
    decoded = base64.b64decode(content_string)
    if 'csv' in filename:
        # Assume that the user uploaded a CSV file
        return pd.read_csv(
            io.StringIO(decoded.decode('utf-8')))
    elif 'xls' in filename:
        # Assume that the user uploaded an excel file
        return pd.read_excel(io.BytesIO(decoded))


@app.callback(Output('datatable-upload-container', 'data'),
              Output('datatable-upload-container', 'columns'),
              Input('datatable-upload', 'contents'),
              State('datatable-upload', 'filename'))
def update_output(contents, filename):
    if contents is None:
        return [{}], []
    df = parse_contents(contents, filename)
    df.to_sql(str(now), engine)
    return df.to_dict('records'), [{"name": i, "id": i} for i in df.columns]



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

The purpose is to drag and drop an excel file into the page and store it in PostgreSQL. This works fine. However, I want to save it under the specific username and the local time. Time works perfectly, but I do not understand how to access the user information within the app. Hope this helps.

That looks like your dash app. I’m wondering how you’re integrating that into your Django app.

Yep, you’re right. I’m fairly new but correct me if I interpreting you incorrectly.

This is my apps.py file in templates folder.

from django.apps import AppConfig


class HomeConfig(AppConfig):
    default_auto_field = 'django.db.models.BigAutoField'
    name = 'home'

You’ve pasted a Dash app. That has nothing to do with Django

You’ve pasted a snippet of a Django apps configuration file. That has nothing to do with your Dash app.

How are the two connected? Where is Django involved with your Dash app? Dash runs on Flask, not Django, that’s why I’m continuing to focus on this point - I don’t see where Django is at all involved with your Dash application.

I see. I am using the Django Plotly Dash module.

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'home.apps.HomeConfig',
    'django_plotly_dash.apps.DjangoPlotlyDashConfig',
    '...',
]

STATICFILES_DIRS = [
    os.path.join(BASE_DIR, "DASHBOARD/static")
]

Ah, ok. That makes sense now.

I’m not familiar with Django Plotly Dash, so I don’t have a specific answer to your question, but a brief review of the docs shows that there are a couple different points of integration available between the two environments.

See:

1 Like

Thanks for your time.

I will look into the sources :slight_smile: