0

i followed the instructions very closely. When i do enter a name it works just fine. However, when i do not enter it, "world" did not show up. only the "hello, " part. This was fine before i use the template. I rerun flask, still same thing. I tried to clear cookies too.

layout.html

<!DOCTYPE html>

<html lang="en">
    <head>
        <meta name="viewport" content="intial-scale=1,width=device-width">
        <title>hello</title>
    </head>
    <body>
        {% block body %}{% endblock %}
    </body>
</html>

index.html

{% extends "layout.html" %}

{% block body %}
    <form action="/greet" method="get">
        <input autocomplete="off" autofocus name="name" placeholder="Name" type="text">
        <button type="submit">Greet</button>
    </form>
{% endblock %}

greet.html

{% extends "layout.html" %}

{% block body %}

    hello, {{ name }}

{% endblock %}

app.py

from flask import Flask, render_template, request

app = Flask(__name__)

@app.route("/")

def index():
    return render_template("index.html")

@app.route("/greet")
def greet():
    name = request.args.get("name","world")
    return render_template("greet.html",name=name)

1 Answer 1

1

From the python docs:

get(key[, default])

Return the value for key if key is in the dictionary, else default. If default is not given, it defaults to None, so that this method never raises a KeyError.

name is in the request.args dictionary, therefore it does not use the default.

All parameters are sent to the server when the request method is GET. Only the entered parameters are sent to the server when request method is POST.

4
  • but in the case where when it is request.form.get, it does get the default value when none is entered. If the below line changes to request.args.get("name",world"), then nothing will show up when no input is entered. In both case, name is in the dictionary? What may cause the difference then? @app.route("/") def index(): if "name" in request.args: return request.form.get("name", "world") return render_template("index.html")
    – TrytoLearn
    Commented Jan 17 at 4:44
  • Added to the answer: it is the difference between a GET and a POST method. Commented Jan 17 at 10:48
  • I actually used the method get, it seem to be the difference between request.form.get and request.args.get?
    – TrytoLearn
    Commented Jan 17 at 15:51
  • Precisely! Here is the flask doc on the subject. Remember get is a python dict method. request is a flask object. Commented Jan 17 at 17:18

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .