Black Lives Matter. Please consider donating to Black Girls Code today.
Dash Enterprise delivers an incredible 21x cost savings 💸Download the e-book!

How to Use Forms with Dash

Hi,

I am trying to build a login page for my first Dash app, but I can’t seem to get it to work with the Form class. I am able to submit and get the proper response when using a Div instead of a Form, but this means the user has to click the submit button instead of being able to press enter. How can I get the below to work using a Form?

import dash
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output, State, Event
from company.security import is_valid_user
 

app = dash.Dash()
  
app.layout = html.Div(children=[
  # product header
  html.Div(children=[
    html.Img(src="http://demo.company.com/design/test_melissa/logo.png", alt="product")
  ], style={'padding' : 7, 'text-align' : 'center'}),
  html.Hr(style={'width' : '30%'}),
  # content
  html.Div(children=[
    html.H3("Please log in", hidden=False, id="page_header"),
    # login form
    html.Form(children=[
      html.P(children=["Username: ", dcc.Input(type='text', id='username', placeholder='username')]),
      html.P(children=["Password: ", dcc.Input(type='password', id='password', placeholder='password')]),
      html.Button(children=['Login'], type='submit', id='login_button')
      ], style={'width' : '30%', 'margin' : '0 auto'}, id="login_form", hidden=False)
    ], style={'display' : 'block', 'text-align' : 'center', 'padding' : 2}),
  html.Br(),
  html.Hr(style={'width' : '30%'}),
  # footer
  html.Div(children=[
    html.Img(src="http://demo.company.com/design/test_melissa/criteologo.png", alt="Logo")
    ], style={'padding' : 7, 'text-align' : 'center'})
  ])

@app.callback(Output('page_header', 'children'),
  events=[Event('login_button', 'click'), Event('login_form', 'click')],
  state=[State('username', 'value'), State('password', 'value')])
def login(username, password):
  if is_valid_user(username, password):
    return "You have been logged in"
  else: 
    return "Wrong username/password please try again."

if __name__ == "__main__":
  app.run_server(debug=True)
2 Likes

Right now, there is no way to subscribe to the enter event.

Did you manage to get login working using Dash? With session tokens and stuff? I am trying to do simple login using Flask back, but can’t get it to work. Any tips or code snippets?