Open In App

Autocomplete input suggestion using Python and Flask

Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we will learn how to give features like auto-completion to the data that is passed from Flask. Autocomplete basically means predicting the rest of the word when the user types something. This way human interaction also increases with every correct prediction. Let’s see how to do the same.

We will be using jquery for autocompletion.

Installation :

To install flask type the below command in the terminal.

pip install flask

First, create a new directory for the project. Inside that create a new file and name it app.py.

app.py

Python3




from flask import Flask, request, render_template
  
  
app = Flask(__name__)
  
  
@app.route("/", methods=["POST", "GET"])
def home():
    if request.method == "GET":
        languages = ["C++", "Python", "PHP", "Java", "C", "Ruby",
                     "R", "C#", "Dart", "Fortran", "Pascal", "Javascript"]
          
        return render_template("index.html", languages=languages)
  
  
if __name__ == '__main__':
    app.run(debug=True)


Then, create a new directory inside the project to hold all the HTML files and name them templates. In this file, we have an input field where the user will type a string and the jquery function will provide the suggestions.

index.html

HTML




<!DOCTYPE html>
<html>
<head>
    <title>AutoComplete</title>
    </script>  
    
    </script>  
    
        rel="stylesheet" type="text/css" />  
</head>
<body>
    <h1>Welcome to GFG</h1>
    <input type="text" id="tags">
    
    <script>
  $( function() {
    var availableTags = [
        {% for language in languages %}
            "{{language}}",
        {% endfor %}
    ];
    $( "#tags" ).autocomplete({
      source: availableTags
    });
  } );
  </script>
    
</body>
</html>


To run this app open cmd or terminal and run the below command.

python app.py

Output:

flask autocomplete



Last Updated : 09 Apr, 2021
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads