Create and connect different page for different row

Hi,

How to create and connect different page for different row?

example,

Customer Product Sale reference Sale Date Details
Customer 1 Desktop sale001 08/11/2022 View
Customer 2 Laptop sale002 08/11/2022 View
Customer 3 Keyboard sale003 11/11/2022 View
Customer 4 Mouse sale004 12/11/2022 View
Customer 5 Pendrive sale005 25/11/2022 View
Customer 6 Hard disk sale006 01/12/2022 View
Customer 7 Mouse pad sale007 13/12/2022 View

Each sale has each table to show the detail. I have a page (which work individually now) to show the table but the table is based on the dropdown menu.
So, how can each row show each detail when click the ‘View’ link?

@beginof,

If you based each page’s layout on the sale reference and gave it a variable in the page’s layout.

dash.register_page(__name__, path_template='/sale/<sale_reference>')

def layout(sale_reference):
    ### your layout

Then you could do this:

[view](f"your base url/sale/{df['sale reference']}")

Hi @jinnyzor,

current version, i will store everything in the same page first before i move it to become 2 pages.
I not sure is it the same for the everything in the same page or split into 2 page.

but, what i’ve try is…

I have try to store the 2nd page layout in the

def layout(sale_reference):
    ### your layout

and return it in the
app.layout = dbc.Container([
     ...
     dbc.Row([
         layout
         
         ]),
     
])


but the page is not return


if i put as layout(), it will show TypeError: layout() missing 1 required positional argument: 'reference'

app.layout = dbc.Container([
     ...
     dbc.Row([
         layout()
         
         ]),
     
])

Hello @beginof,

You will need to register the second page with dash pages. And then create your entire layout under the layout function and return it.

def layout(sale_reference=None):
     layout = dbc.Container([dbc.Row()])
     return layout

@beginof

You can find a minimal example here (see #12 ) GitHub - AnnMarieW/dash-multi-page-app-demos: Minimal examples of multi-page apps using the pages feature in dash>=2.5.1

HI @AnnMarieW,

With this solution, can I link/ share the dropdown menu?

example, page1 store dropdown menu and page2 store the table.
page2 table will based on the page1 dropdown selection to show the data.

Hi @jinnyzor,

I had register the page2 under dash pages

dash.register_page(__name__, path_template='/profile/<reference>')

and the use_pages in the page1.

app= dash.Dash(__name__,external_stylesheets=[dbc.themes.BOOTSTRAP],
                meta_tags=[{'name': 'viewport',
                            'content': 'width=device-width, initial-scale=1.0'}],
                use_pages=True
                )

however, how can I connect the page1 dropdown into page2 table and the page1 view url able to display the data only for its row?

You’ll need to store the value in a dcc.store, or you could pass it with a query string to the page.

The dcc.store would probably be easier.

store the dropdown or the page2 in dcc.store?

The drop-down value. Then use it in a callback on the page-2

Hi,

May I know which part i m getting wrong? because keep on getting this error:

File “”, line 1
Sale Date ==
^
SyntaxError: invalid syntax

I believe is due to the dcc.store…

code:

@callback(
    Output('date_dd','options'),
    Input('product_dd', 'value')
    )


def update_dd (product_dd):
  
    date = df.drop_duplicates(['Sale Date'], inplace= False)
    
    relevant_date = date[ df['Product'] == product_dd]['Sale Date'].values.tolist()

    date_option= [dict(label=x,value=x)for x in relevant_date]
    
    
    return date_option



@callback(
    Output('store','data'),
    Input('date_dd', 'value')
    )


def get_data (ddate):
  
    dff = df.query (f'Sale Date == {ddate}')
    
    store = {
        'data': dff.to_dict('records'),
        'colums': [{'name': i, 'id': i} for i in dff.columns]
        
        }
    
    return store


# #TABLE

@callback(
    Output('tablelisting', 'data'),
    Output('overmessage', 'is_open'),
   # Input('date_dd', 'value'),
    Input('store', 'data')

    )

def update_table(selection):
    if len (selection) == 0:
        return dash.no_update
    
    else:  
        dff = df[(df['Sale Date'] == selection)] 


         dff['view'] = '[View](https://dash.plotly.com/datatable)' 

        
        columns = dff[['Customer', 'Product', 'Sale reference', 'Sale Date',  'view']]

        data= columns[0:3].to_dict('records')
        
       
        return data, len(dff)>3

Instead of trying to store the df, store the drop-down value and then load it like you are doing previously when using the dd value.

this part is not storing the dropdown value?

1 Like

That is storing the data.

I was saying just store the value straight and then on the page, use it to query like normal.

Hi,

I had tried to store the dropdown value in dcc.Store and yes, the store is able to perform.
However, the 2nd page still not able to display based on the 1st page ticker.

dataframe:

Reference ID Customer Product Sale reference Sale Date
1 Customer 1 Desktop sale001 08/11/2022
2 Customer 2 Laptop sale002 08/11/2022
3 Customer 3 Keyboard sale003 11/11/2022
4 Customer 4 Mouse sale004 12/11/2022
5 Customer 5 Pendrive sale005 25/11/2022
6 Customer 6 Hard disk sale006 01/12/2022
7 Customer 7 Mouse pad sale007 13/12/2022
8 Customer 8 Desktop sale008 08/11/2022
9 Customer 9 Laptop sale009 08/11/2022
10 Customer 10 Keyboard sale010 11/11/2022
11 Customer 11 Mouse sale011 12/11/2022
12 Customer 12 Pendrive sale012 25/11/2022
13 Customer 13 Hard disk sale013 01/12/2022
14 Customer 14 Mouse pad sale014 13/12/2022

expected output:
page1


`page2`

image




Below are the code:

app.py

import plotly.express as px
from plotly.offline import plot

import dash
from dash import dcc, html, callback
# import dash_core_components as dcc
# import dash_html_components as html
from dash.dependencies import Output,Input, State
import dash_bootstrap_components as dbc
from dash import dash_table
from dash_table import DataTable, FormatTemplate


import pandas as pd
import pandas_datareader.data as web


from datetime import date, datetime


import pyodbc
import os
import psycopg2

from plotly.io import write_image
import flask
import base64


# Dashboard layout
app= dash.Dash(__name__,external_stylesheets=[dbc.themes.BOOTSTRAP],
                meta_tags=[{'name': 'viewport',
                            'content': 'width=device-width, initial-scale=1.0'}],
                use_pages=True
                )


app.layout = dbc.Container([
    

    dbc.Row([#html.H5('test'),
              dash.page_container
        ]),
    ],
    fluid = True
    
    
    )           


if __name__ == "__main__":
    app.run_server(debug=True, port=1015)




page1.py

import plotly.express as px
from plotly.offline import plot

import dash
from dash import dcc, html, callback
from dash.dependencies import Output,Input, State
import dash_bootstrap_components as dbc
from dash import dash_table
from dash_table import DataTable, FormatTemplate
import dash_bootstrap_components as dbc

import pandas as pd
import pandas_datareader.data as web

from datetime import date, datetime

import pyodbc
import os
import psycopg2

from plotly.io import write_image
import flask
import base64

dash.register_page(__name__, 
                   path="/",
                   title= 'Main')

df= pd.read_csv("dataframe.csv")

product_cat = list(df['Product'].unique()) 


layout = dbc.Container([
    
    dcc.Store(id = 'store', storage_type = 'session'), #data={} , data=df.to_dict("records")
    dcc.Store(id = 'store1', storage_type = 'session'),
    dbc.Row([
        dbc.Col(html.H1("Listing",
                        className = 'text-center text-primary, mb-4 '
                        ,style={"textDecoration":"underline",'font-weight': 'bold'}),
                width=12
                ),
      
        ]),
    html.Br(),
    html.Br(),
    
    dbc.Row([
       dbc.Col([
           html.H3('Product'
                    ,style={'font-size': '25px'}
                   ),
           
           ], width=3, md=4),
       
       dbc.Col([            
           dcc.Dropdown(id='product_dd', value= None, 
                          options = [{'label':x, 'value':x} 
                                    for x in product_cat],
                          
                          searchable = True, search_value='',
                          placeholder= 'Please select ...',
                          clearable= True
                          ),
           
           ], width=3, md=4),    
       
       
       ]),
    html.Br(),
    
    
    
    dbc.Row([       
        dbc.Col([            
            html.H3('Sale Date'
                    ,style={'font-size': '25px'}
                    ),
            
            ], width=3, md=4),
    
        dbc.Col([            
            dcc.Dropdown(id='date_dd', value= '',                         
                          searchable = True, search_value='',
                          placeholder= 'DD/MM/YYYY',
                          clearable=True
                          
                          ),
                    
            ], width=3, md=4),
        
        dbc.Col([            
            html.H3('i.e: 15/11/2022'
                    ,style={'font-size': '15px'}
                    ),
            
            ], width=3, md=4),
        ], ), #style={"flexWrap": "wrap", "width":"250px"}
    html.Br(),

    
    dbc.Row([
        dbc.Col([
            html.P("Listing",
                    style={"textDecoration":"underline"}),
            
         
            dash_table.DataTable(id='tablelisting', 
                                    columns=[
                                        {'name': 'Customer', "id": 'Customer'},
                                        {'name': 'Product', 'id':'Product'},
                                        {'name': 'Sale Date', 'id':'Sale Date'},
                                        {'name': 'Details', 'id':'view', 'type':'text', 'presentation':'markdown'},
 
                                        
                                        ],
                                  style_cell={'textAlign': 'left'},
                                  # markdown_options = {'link_target': '_self'}
                                  
                                  ),
           
                ]),
            ]),   
  
    ],   
    
    )      




        
@callback(
    Output('date_dd','options'),
    Input('product_dd', 'value')
    )


def update_dd (product_dd):
  
    date = df.drop_duplicates(['Sale Date'], inplace= False)
    
    relevant_date = date[ df['Product'] == product_dd]['Sale Date'].values.tolist()

    date_option= [dict(label=x,value=x)for x in relevant_date]
    
    
    return date_option

   


@callback(
    Output('store','data'),
    Input('date_dd', 'value'),

    )


def get_data (ddate):
    
    return ddate    


# #TABLE

@callback(
    Output('tablelisting', 'data'),
    Input('store', 'data')

    )

def update_table(selection):
    if len (selection) == 0:
        return dash.no_update
    
    else:  
        dff = df[(df['Sale Date'] == selection)] 
               
        equit = dff['Customer'].to_list()       

        dff['view'] = [f"[View](/details/{ticker})" for ticker in equit]               
        
       
        columns = dff[['Customer', 'Product', 'Sale Date','view']]

        
        data= columns.to_dict('records')      
        
        
        return data




page2.py

import plotly.express as px
from plotly.offline import plot

import dash
from dash import dcc, html, callback
from dash.dependencies import Output,Input, State
import dash_bootstrap_components as dbc
from dash import dash_table
from dash_table import DataTable, FormatTemplate
import dash_bootstrap_components as dbc

import pandas as pd
import pandas_datareader.data as web

from datetime import date, datetime

import pyodbc
import os
import psycopg2

from plotly.io import write_image
import flask
import base64

import json



def title(ticker=None):
    return f"{ticker} Analysis"


dash.register_page(__name__, 
                   path_template='/details/<ticker>',
                   path="/details/customer1",
                   title = title)



    
    
# # read data from csv
df= pd.read_csv("dataframe.csv")

    
def layout(ticker= None, **other_unknown_query_strings):
    layout = dbc.Container([
        
        dbc.Row([
            dbc.Col([
                html.P(f"Profile: {ticker}",
                        style={"textDecoration":"underline"}),
                
                                        
                dash_table.DataTable(id='tableprofile', 
                                        columns=[
                                            {'name': '', "id": 'header'},
                                            {'name': 'Information', "id": 'info'},
    
                                                ],  
                                      ),
                html.Br(),
                
                    ]),
                ]),
        
    ])

    return layout

    
@callback(
    Output('tableprofile', 'data'), 
    Input('store','data')

    )

def update_table(selection): 
    if len (selection) == 0:
        return dash.no_update
    
    else:

        dff = df[df['Sale Date'] == selection]  
        
        transpose = dff.melt(id_vars = ['Reference_ID']
                  ,var_name = ['header']
                  ,value_name = 'info')
        
        
        info = transpose[transpose['header'].isin(['Customer','Product', 'Sale reference, 'Sale Date' ])]

        
        
        columns = info[['header','info']]


        data= columns.to_dict('records')

       
        return data