Home > Mobile >  Flask: 1 form, 2 buttons. (google search clone)
Flask: 1 form, 2 buttons. (google search clone)

Time:10-31

how I can get different path from different buttons? I want implement "i'm feeling lucky" functionality using /wiki/?q={args} from a button, but I think I don't know how to do that.

my code: HTML:

<div class="search-bar">
            <form action="/search" method="get">
                <input type="search" name="q" autocomplete="false" autofocus>
                <button type="submit">Goggle Search</button>
                <button  type="submit">I'm Feeling Lucky</button>
            </form>
        </div>

Flask:

@app.get("/search")
def search():
    """
    1. Capture the word that is being searched
    2. Search for the word on Google and display results
    """
    args = request.args.get("q")
    return redirect(f'https://google.com/search?q={args}')

look and feel: enter image description here

CodePudding user response:

I found the solution based in "formaction", within the buttons. "formaction" works like whether each button had different endpoints, a button trigger a specific endopoit and other buttons another endpoints.

HTML:

<form  method="get">
                <input name="q" autocomplete="false" autofocus>
                <button formaction='search' type="submit" name="1" value="search" >Goggle Search</button>
                <button formaction='wiki/'  type="submit" name="1" value="wiki" >I'm Feeling Lucky</button>
            </form>
        </div>

flask

@app.get("/search")
def search():
    """
    1. Capture the word that is being searched
    2. Search for the word on Google and display results
    """
    args = request.args.get("q")
    return redirect(f'https://google.com/search?q={args}')

@app.get("/wiki/")
def wiki():
    """
    
    """
    args = request.args.get('q')
    return redirect(f'https://en.wikipedia.org/wiki/{args}')

google "I'm Feeling lucky" work in totally another way but, it's ok.

CodePudding user response:

Please check the semantics for <form>. Ideally there will be only 1 type="submit" in the form and it is meant to send the form content to a server or a defined action script. You can achieve what you with the button type, but you'll need to catch the event and identify which one was clicked.

  • Related