Muhammad Rafeh Atique
Muhammad Rafeh Atique

Reputation: 872

How to know which form is submitted to the flask web server

This code is very big, in this code I am taking data from forms and I don't know from which form the user has triggered the button. So, in code I am identifying where it has values and where not which has make my code big that's a very awkward and maybe this is not a professional way to do this. If there is another way to minimize/upgrade this code, please let me know.

@app.route('/search', methods=['POST','GET'])
def search():
    if request.method=='POST':
        """Fetching all the Inputs"""
        isbn = request.form.get('isbn')
        title = request.form.get('title')
        author = request.form.get('author')

        if isbn is None:
            if title is None:
                if author is not None:
                    """Here ONly we have author input"""
                    info = db.execute("SELECT * FROM books WHERE author = :author",{'author':author}).fetchall()
                else:
                    """Here no one"""
            else:
                """Here title has value"""
                if author is not None:
                    """here title and author has only value"""
                    info = db.execute("SELECT * FROM books WHERE author = :author OR title = :title",{'author':author, 'title':title}).fetchall()
                else:
                    info = db.execute("SELECT * FROM books WHERE title = :title",{'title':title}).fetchall()

        else:
            if title is None:
                if author is not None:
                    """Here ONly we have author and isbn input"""
                    info = db.execute("SELECT * FROM books WHERE author = :author OR isbn = :isbn",{'author':author, 'isbn':isbn}).fetchall()
                else:
                    info = db.execute("SELECT * FROM books WHERE isbn = :isbn",{'isbn':isbn}).fetchall()
            else:
                """Here title and isbn has value"""
                if author is not None:
                    """here title, isbn, author has only value"""
                    info = db.execute("SELECT * FROM books WHERE author = :author OR ibsn = :isbn OR title = :title",{'author':author, 'ibsn':ibsn, 'title':title}).fetchall()
                else:
                    """here title, isbn has only value"""
                    info = db.execute("SELECT * FROM books WHERE title = :title OR isbn = :isbn",{'title':title, 'isbn':isbn}).fetchall()

Html code look like this; <html>

<div class="row" style="margin-top: 15px; padding: 2px;">
        <nav class="navbar navbar-light bg-light">
            <form class="form-inline" action="{{ url_for('search') }}" method="post">
                <input class="form-control mr-sm-2" name="isbn" type="search" placeholder="Enter Isbn" aria-label="Search">
                <button class="btn btn-outline-success my-2 my-sm-0" type="submit">Search</button>
            </form>
        </nav>
        <nav class="navbar navbar-light bg-light">
            <form class="form-inline" action="{{ url_for('search') }}" method="post">
                <input class="form-control mr-sm-2" name="title" type="search" placeholder="Enter Title" aria-label="Search">
                <button class="btn btn-outline-success my-2 my-sm-0" type="submit">Search</button>
            </form>
        </nav>
        <nav class="navbar navbar-light bg-light">
            <form class="form-inline" action="{{ url_for('search') }}" method="post">
                <input class="form-control mr-sm-2" name="author" type="search" placeholder="Enter Author" aria-label="Search">
                <button class="btn btn-outline-success my-2 my-sm-0" type="submit">Search</button>
            </form>
        </nav>
    </div>
    <div>
        <form id="center" action="{{ url_for('search') }}" method="post">
                <button type="button" class="btn btn-primary">Search</button>
        </form>
    </div>

Upvotes: 2

Views: 797

Answers (1)

Saadi Toumi Fouad
Saadi Toumi Fouad

Reputation: 2829

Well in order to do it in an easy and more professional way you can add a query string to the requested URL for submitting each form like this simple example:

forms.html

<form action="/reg?f=f1" method="post">
  <input type="text" name="username" placeholder="username">
  <input type="submit" value="submit">
</form>

<form action="/reg?f=f2" method="post">
  <input type="email" name="email" placeholder="email">
  <input type="submit" value="submit">
</form>

so the first form and the second one can be ientified because of the query string, so if the f equals "f1" then it's the first form otherwise it's the second one

server_app.py

from flask import Flask, request, render_template

app = Flask(__name__)

@app.route('/reg', methods=['GET', 'POST'])
def sign_up():
  # if the method is POST then the user is submitting a form otherwise he's just requesting page content
  if request.method == "POST":
    # the first form being submitted
    if request.args.get("f") == "f1":
      print(request.form["username"])
    # the second form being submitted
    else:
      print(request.form["email"])
  # always the same page only for testing
  return render_template("forms.html")

app.run(host='127.0.0.1',port=8080,debug=True)

Upvotes: 4

Related Questions