Want to dynamical html.Div id - python

app = Dash(__name__, suppress_callback_exceptions=True)
server = app.server
app.layout = html.Div([
dcc.Location(id='url', refresh=False),
html.Div(id={}).format('page-content'+ uuid.uuid4().hex),
html.Div(id={}).format('page-graph'+uuid.uuid4().hex),
# uuid.uuid4().hex,
# html.Div(id='page-content'),
# html.Div(id='page-graph')
], style={'width': '100%', 'height': '486px'}) #486px
#app.callback(
Output('page-content'+ uuid.uuid4().hex', 'children'),
Input('url', 'search')
)
I want to variable html.Div(id) when i receive URL
I Try this But Output to Id is not same
What can i do??

Related

How to have a customized CSS style for a bootstrap component?

I have the code below that has a bootstrap offcanvas at the left. I wondered how I can change the width of the collapsed sidebar. Bootstrap does not have a style tag to do that. I searched and I saw some people suggested using a customized CSS style to define new styling. Can you please help me with that I am pretty new to styling, and I don’t know where I should start.
from dash import Dash, html, dcc, Input, Output, State
import dash_bootstrap_components as dbc
from dash_iconify import DashIconify
app = Dash(__name__, use_pages=True, external_stylesheets=[dbc.themes.SPACELAB])
sidebar = dbc.Nav([
dbc.NavLink([
html.Div(page["name"], className="ms-2"),
], href=page["path"],
active="exact",
)
for page in dash.page_registry.values()
], vertical=True,
pills=True,
className="bg-light",
)
download_icon = DashIconify(icon='ic:baseline-menu', width=40, style={})
app.layout = dbc.Container([
dbc.Row([
dbc.Col(
html.Div("Drilling Dashboard",
style={'fontSize': 40,
'textAlign': 'center',
'color': 'white'}
)
),
dbc.Col([
dbc.Button([download_icon, ''], id="open-offcanvas", n_clicks=0),
], width=1,
style={'margin-right': 0,
'padding': 5}
),
]),
html.Hr(
style={'margin-top': 0}
),
dbc.Row([
dbc.Offcanvas(
dbc.Col([sidebar], width=5), id="offcanvas", title="Title", is_open=False, style={'horizontal-width': 10}
),
]),
dbc.Row([
dbc.Col([dash.page_container], xs=8, sm=8, md=10, lg=10, xl=10, xxl=10)
])
], fluid=True,
style={'background-color': 'black'})
#app.callback(
Output("offcanvas", "is_open"),
Input("open-offcanvas", "n_clicks"),
[State("offcanvas", "is_open")],
)
def toggle_offcanvas(n1, is_open):
if n1:
return not is_open
return is_open
if __name__ == "__main__":
app.run(debug=True)
You can change the width of sidebar by the following attribute:
dbc.Offcanvas(
dbc.Col([sidebar], width=8),
id="offcanvas",
title="Title",
is_open=False,
style={'width': 100} #<---- this attribute instead of horizental-width
)
Output

callback functions based on modal popup data not working (dash)

I am new to dash and am having trouble with writing a more complex callback function. The steps to my app are:
press a button to open a modal popup.
select options from a drop-down on the popup, which changes input options.
choose the desired input options
click a "submit" button to print (ultimately write) the input data.
I suspect I need either pattern matching callbacks, or chained callbacks because the errors I get say:
"Attempting to connect a callback Input item to component:
"id"
but no components with that id exist in the layout."
This is because the inputs don't appear until the modal popup and drop-down are activated.
Below is a minimal example with all the important layout features and should run on any machine. I specifically need help getting the last callback in the proper format to print the selected data from the modal drop-down.
Thanks!
import time
import dash
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output, State
import dash_bootstrap_components as dbc
from dash_bootstrap_templates import load_figure_template
################################################################################################
app = dash.Dash(external_stylesheets=[dbc.themes.CERULEAN])
report_list = [
{"label": "drop down 1", "value": 1},
{"label": "drop down 2", "value": 2},
]
body1 = html.Div([
html.H6(
"Enter value (required)"
),
dcc.Input(
id = 'report-1',
type = 'text',
placeholder = "value",
debounce=True,
required=True,
),
html.Div(html.Br(),),
html.H6(
"Choose a new reach type (required)"
),
dcc.RadioItems(
id = 'type_radio',
options=[
{'label':'radio1','value':1},
{'label':'radio2', 'value':2},],
className='btn-group-vertical p-2'),
])
body2 = html.Div([
html.H6(
"Enter value (required)",
),
dcc.Input(
id = 'report-2',
type = 'text',
placeholder = "value",
debounce=True,
required=True,
),
html.Div(html.Br(),),
html.H6(
"Input 1 (required)",
),
dcc.Input(
id = 'input1',
type = 'text',
placeholder = "input 1",
debounce=True,
required=True,
),
html.Div(html.Br(),),
html.H6(
"Input 2 (required)"),
dcc.Input(
id = 'input2',
type = 'text',
placeholder = "input 2",
debounce=True,
required=True,
),
])
################################################################################################
report_overlay = dbc.Modal(
[
dbc.ModalBody(
html.Div(children=[
html.Div([
'Description...'],
id="report-md"),
html.Div([
html.H5([
'Choose an option:'
]),
]),
html.Div([
dcc.Dropdown(
id='Report_DropBox',
options=report_list,
style={
# "textAlign":"center",
"width":"60%",
}
),
]),
html.Div([html.Br()]),
html.Div(id='report-options'), #different options for reporting a reach.
html.Div([html.Br()]),
html.Div([
dbc.Button(
"Submit",
id="report-submit",
outline=False,
color="secondary",
size="sm",
style={
"textTransform": "none",
"width":"30%"
},
),
]),
],
),
),
html.Div([html.Br()]),
html.Div(
id='submit_status',
style={"textAlign":"center", "width":"50%"}), #print status of submission.
html.Div([html.Br()]),
dbc.ModalFooter(
dbc.Button(
"Close",
id="report-close",
className="howto-bn"
)),
],
id="report-modal",
size="lg",
)
################################################################################################
app.layout = html.Div([
html.Br(),
dbc.Button(
"Report Reach",
id="report-open",
outline=False,
color="red",
style={
# "textTransform": "none",
"margin-right": "5px",
"color":"white",
"background-color":"#C42828",
"textAlign":"center",
},
),
report_overlay,
],style={"textAlign":"center"},
)
################################################################################################
##### callbacks
# Callback for modal popup
#app.callback(
Output("report-modal", "is_open"),
[Input("report-open", "n_clicks"), Input("report-close", "n_clicks")],
[State("report-modal", "is_open")],
)
def toggle_modal(n3, n4, is_open):
if n3 or n4:
return not is_open
return is_open
# Callback for different layouts based on drop down.
#app.callback(Output('report-options', 'children'),
Input('Report_DropBox', 'value'))
def render_content(report):
if report == 1:
return body1
if report == 2:
return body2
#attempted callback to print data based on modal input.
#app.callback(
Output("submit_status", "children"),
[
Input("Report_DropBox", "value"),
Input("report-1", "value"),
Input("report-2", "value"),
Input("type_radio", "value"),
Input("input1", "value"),
Input("input2", "value"),
Input("report-submit","n_clicks")
],
)
def print_report(dropbox, r1, r2, type, ip1, ip2, submit):
if submit:
if dropbox == 1:
r = r1
data = type
date_stamp = time.strftime("%d-%b-%Y %H:%M:%S", time.gmtime())
List = [r,data,date_stamp]
statement = html.Div([List])
elif dropbox == 2:
r = r2
data1 = ip1
data2 = ip2
date_stamp = time.strftime("%d-%b-%Y %H:%M:%S", time.gmtime())
List = [r,data1,data2,date_stamp]
statement = html.Div([List])
return statement
if __name__ == '__main__':
app.run_server(debug=True)

Plotly Dash Update Drop Down from call back where data frame inside the call back

I am trying to update the drop-down menu from the data frame column value where my data frame is generated inside call back since I am taking user inputs and extracting some data from API.
I want to create a filter in the dropdown that's why I want that drop-down updated dynamically using the data frame column.
so in a call back I have df['name_id'] through which I want to update the segment dropdown.
I have taken the only important line to break in my code since the code is too lengthy:
import dash_core_components as dcc
import dash_html_components as html
import dash_bootstrap_components as dbc
import datetime
import dash_table
import httplib2
import pandas as pd
import requests
import io
import time
from Dash_App.app import app
from dash.dependencies import Input, Output, State
from oauth2client import GOOGLE_REVOKE_URI, GOOGLE_TOKEN_URI, client
from oauth2client import client, GOOGLE_TOKEN_URI
from datetime import date, timedelta
from apiclient import discovery
row1 = html.Div(
[
dbc.Row([
dbc.Col([
dbc.Input(id="client_id",
type="text",
placeholder="Client ID",
style={'width': '150px'}, persistence=True,
persistence_type='memory'),
]),
], align="center"),
], style={'margin-top': 20, 'margin-left': -90}
)
row2 = html.Div([
dbc.Row([
dbc.Col([
dcc.Dropdown(
id='segment',
options=[{'label': i, 'value': i} for i in "what"],
multi=True,
style={'width': '250px'},
placeholder='Segment'),
]),
])
])
tab_2_layout = dbc.Container(children=[
row1,
html.Br(),
row2,
]
)
#app.callback(Output('output_div-ga', 'children'),
[Input('submit-button', 'n_clicks')],
[State('client_id', 'value'),
],
)
def ga_output(clicks, client_id):
if clicks is not None:
my_client_id = client_id
credentials = client.OAuth2Credentials(
access_token=None, # set access_token to None since we use a refresh token
client_id=my_client_id)
credentials.refresh(httplib2.Http()) # refresh the access token (optional)
http = credentials.authorize(httplib2.Http()) # apply the credentials
service_v3 = discovery.build('analytics', 'v3', http=http)
segments = service_v3.management().segments().list().execute()
df = pd.DataFrame(segments['items'])
df = df[['name', 'id']]
df['name_id'] = df.name.astype(str).str.cat(df.id.astype(str), sep=':')
return html.Div([dcc.Store('memory'),
dash_table.DataTable(
id='table',
columns=[{"name": i, "id": i} for i in dff.columns],
data=dff.to_dict("rows"), persistence=True, persistence_type='memory',
export_format="csv",
),
])
I am able to solve this by generating form inside call back.
return html.Div([
dbc.Row([
dbc.Col([
dcc.Dropdown(
id='segment',
options=[{'label': i, 'value': i} for i in df['name_id'].unique()],
persistence=True, persistence_type='memory',
multi=True,
style={'width': '250px', 'margin-left': -250, 'margin-top': 10},
placeholder='Segment'),
]), ]), ])
What worked for me was to give each column that you want to edit an id, make it editable and then update the dropdown options in the DataTable. I also returned the whole DataTable in my callback.
app.callback(
Output("table-dropdown-container", "children"),
Input("input-data-table-id", "data"),
)(self.update_unlabelled_shops_table)
...
dt = (
dash_table.DataTable(
id='table-id',
data=df.to_dict("records"),
columns=[{"name": i, "id": i} if i != column_name else {"name": i, "id": i, "editable": True, "presentation": "dropdown"} for i in df.columns],
page_size=8,
dropdown={
column_name: {
"options": [
{"label": i, "value": i}
for i in df[column_name].unique()
]
},
},
),
)
return dt
except Exception as e:
print(e)
return [None]
And to create your div block.
def create_div(self):
return html.Div(
[
dash_table.DataTable(
id='table-id',
columns=[],
editable=True,
dropdown={},
),
html.Div(id="table-dropdown-container"),
]
)
Hope this helps somebody...

Dash range slider with input on each side

I am quite new to front-end development and HTML and I'm struggling to understand how to order a range slider with two inputs in the same line when using Dash
I have tried to separate the html.Div, Putting the components in the same Div without separating them
adjust the different parameters and some morebut I still can't get it to appear the way I want
what I want:
what I have:
My code (that reproduce what I have):
import dash
import dash_core_components as dcc
import dash_html_components as html
app.layout = html.Div([
html.Div([
html.Div([dcc.Input(
id='slider-min-value',
placeholder=str(min_value))],
style={'width': '10%'}
),
html.Div([dcc.RangeSlider(
id='condition-range-slider',
min=0,
max=30,
value=[10, 15],
allowCross=False)],
style={'width': '25%'}
),
html.Div([dcc.Input(
id='slider-max-value',
placeholder=str(max_value))],
style={'width': '10%'}
),
],
style={'display': 'inline-block'})])
if __name__ == '__main__':
app.run_server(debug=True)
what do I need to do in order to get the rangeslider and the inputs to appear the way I want?
Ok, using {"display": "grid", "grid-template-columns": "10% 40% 10%"} gave me what I wanted.
layout:
app.layout = html.Div(
html.Div(
[
dcc.Input(type='text', value=min_value),
dcc.RangeSlider(
id='condition-range-slider',
min=0,
max=30,
value=[10, 15],
allowCross=False
),
dcc.Input(type='text', value=max_value)
],
style={"display": "grid", "grid-template-columns": "10% 40% 10%"}),
style={'width': '20%'}
)
what I got:
You can try updating the html.Div style with 'float': 'left',
import dash
import dash_core_components as dcc
import dash_html_components as html
app = dash.Dash(__name__)
app.layout = html.Div(
[
html.Div(
style={'width':'10%', 'float':'left', 'marginLeft': 20, 'marginRight': 20},
children=[
dcc.Input(id='slider-min-value')
]
),
html.Div(
style={'width':'50%', 'float':'left','marginLeft': 20, 'marginRight': 20},
children=[
dcc.RangeSlider(
id='condition-range-slider',
min=0,
max=30,
value=[10, 15],
allowCross=False
)
]
),
html.Div(
style={'width':'10%', 'float':'left','marginLeft': 20, 'marginRight': 20},
children=[
dcc.Input(id='slider-max-value')
]
),
])
if __name__ == '__main__':
app.run_server(debug=True)

Make interactive bar plot with 2 columns and date column as dropdown using Dash?

I am making a bar plot using Dash with date column as the dropdown. This would be an interactive graph which would change if user changes the date dropdown.
Below is the sample dataframe:
message Date Count
Hi 01/08/19 10
Bye 01/08/19 20
GN 01/08/19 30
Hi 02/08/19 15
Bye 02/08/19 25
GN 02/08/19 35
Below is my current code. I am using Dash for the first time, so there is some error.
app = dash.Dash()
app.layout = html.Div([
dcc.Dropdown(
id = 'first_dropdown',
options = df.Date,
placeholder='Select a Date'
)
html.Div(id='output-graph')
])
#app.callback(
Output(component_id='output-graph', component_property='children'),
[Input(component_id='first_dropdown', component_property='options')]
)
return dcc.Graph(id = 'Bar_Plor',
figure = {
'data' : [
{'x':df.message, 'y':df.count, 'type':'bar', 'name':'First Chart'}
]
})
if __name__ == '__main__':
app.run_server(port=4050, debug=True)
Here is a code that works for you.
import pandas as pd
import dash
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output
app = dash.Dash()
df = pd.DataFrame({'message': ['Hi', 'Bye', 'GN', 'Hi', 'Bye', 'GN'],
'Date': ['01/08/19', '01/08/19', '01/08/19', '02/08/19', '02/08/19', '02/08/19'],
'Count': [10, 20, 30, 15, 25, 35]})
app.layout = html.Div([
dcc.Dropdown(
id = 'first_dropdown',
options = df.Date,
placeholder='Select a Date'
),
html.Div(id='output-graph')
])
#app.callback(
Output(component_id='output-graph', component_property='children'),
[Input(component_id='first_dropdown', component_property='options')]
)
def update_output_div(input_value):
return dcc.Graph(id = 'Bar_Plor',
figure = {
'data' : [
{'x':df.message, 'y':df.Count, 'type':'bar', 'name':'First Chart'}
]
})
if __name__ == '__main__':
app.run_server(port=4050, debug=True)
app = dash.Dash()
def createObject(x):
options = []
for i in x:
options.append({
'label': i,
'value': i
})
return options
df = pd.DataFrame({'message1': ['Hi', 'Bye', 'GN', 'Hi', 'Bye', 'GN'],
'date1': ['01/08/19', '01/08/19', '01/08/19', '02/08/19', '02/08/19', '02/08/19'],
'count1': [10, 20, 30, 15, 25, 35]})
app.layout = html.Div([
html.Br(),
html.Br(),
dcc.Dropdown(
id = 'first_dropdown',
options = createObject(df.date1.unique()),
placeholder='Select a Date'
),
html.Div(id='output-graph')
])
#app.callback(
Output(component_id='output-graph', component_property='children'),
[Input(component_id='first_dropdown', component_property='value')]
)
def update_output_div(input_value):
return dcc.Graph(id = 'Bar_Plot',
figure = {
'data' : [
{'x':df[df['date1']==input_value].message1, 'y':df[df['date1']==input_value].count1, 'type':'bar', 'name':'First Chart'}
]
})
app.run_server(port=4050)
this works for me

Categories