Search code examples
htmlflaskjinja2

How to use html input data in jinja {{url_for()}}


I am using Flask to render templates in html using jinja.

I have made a form in html

<form class="container-fluid">
    <div class="input-group col-4">
        <span class="input-group-text" id="basic-addon1">?img=</span>
        <input type="text" class="form-control" placeholder="Image URL" aria-label="Image URL"
            aria-describedby="basic-addon1" name="img_arg_input">
    </div>
    <a href="{{ url_for('home', img='') }}" class="btn btn-outline-primary">
        Submit
    </a>
</form>

I'm running this on Flask on a local server http://127.0.0.1:5000

In the url_for I am using img='' for giving argument to the link. Currently it loads http://127.0.0.1:5000/home?img= because I'm giving empty string. I want to replace that empty string with whatever I write in the input html tag.

My home function in flask application looks like this:

@application.route('/home')
def home():
    home_data = {
        'message': 'Home'
    }
    img_file = request.args.get("img")
    if img_file:
        home_data['img_file'] = img_file
    return render_template('home.html', home_data = home_data)

Here I'm calling request.args.get and using that value which is seperate.

My main concern is how to use whatever I write in my input html tag in the url_for as an argument

Or am I looking at this problem for a wrong perspective, any help is appreciated.

EDIT: I have a follow up question, what if in future I want to create something like this

@application.route('/data/<name>', methods=['GET','POST'])
def data(name):
    ...

How will I go about using url_for here?


Solution

  • If you want to use request.args.get and transport the parameters within the URL, you need a form with the GET method, which corresponds to the default value.
    This form can be submitted via either an input or a button of type submit, not via an anchor.

    <form>
        <div>
            <label for="input-id">My Input:</label>
            <input type="text" name="input-name" id="input-id" />
        </div>
        <button type="submit">Submit</button>
    </form>
    

    The name of the input field corresponds to the key with which the value can be queried on the server side.

    @app.route('/')
    def index():
        my_input = request.args.get('input-name')
        print(my_input)
        return render_template('index.html')
    

    Using url_for is only necessary if the form is to be sent to a different endpoint than the template comes from. In this case, the action parameter of the form must be assigned.

    If you want to upload an image, it is advisable to take a look at the documentation under "Uploading Files".

    You can find the use of variable rules together with url_for in the sections "Variable Rules" and "URL Building".