简体   繁体   中英

To retain the form values in the jinja template

I have a form that I am using for post the data

<form enctype="multipart/form-data" method="post" action="">
  <div class="form-group">
     <label>Application Name <span class="mandatory">*</span></label>
     <input type="text" class="form-control" name="app_name" id="appname" required maxlength="40">
     <button>submit</button>
   </div>
 </form>

In flask i am fetching the form data and trying to do post method

if request.method == "POST":
   application_data = request.form.to_dict()
   postedata = post(application_data )
   if posteddata:
      print("sucessfully posted")
   else:
      print("unsucessful")
      return render_template("application/addapplication.html", data=application_data)

but what I want is when else part executes that means post data doesnot happens i want to retain the values in the form. but, since here page will reload the form data is disapperaring. please can anyone help me in this?

<input type="text" value="{{ request.form.get('app_name','')}}" class="form-control" name="app_name" id="appname" required maxlength="40">

For Select tag, Let's take the data from the Flask flask_option = 'batman'.

<select>
  <option {% if flask_option == "superman"%} selected {% endif %} value="superman">Clark</option>
  <option {% if flask_option == "batman"%} selected {% endif %} value="batman">Bruce</option>
  <option {% if flask_option == "wonderwomen"%} selected {% endif %} value="wonderwomen">Diana</option>
  <option {% if flask_option == "aquaman"%} selected {% endif %} value="aquaman">Arthur</option>
</select>

If you are using API for the select options, let's take the API response like this,

{'response': [
    {'value': 'superman', 'inner_text': 'Clark'},
    {'value': 'batman', 'inner_text': 'Bruce'},
    {'value': 'aquaman', 'inner_text': 'Arthur'},
    {'value': 'wonderwomen', 'inner_text': 'Diana'}
]}

You can iterate over the API to generate the select tag,

<select>
  {% for value, text in varible_name.response %}
     <option {% if flask_option == value %} selected {% endif %} value = '{{value}}'> {{text}} </option>
  {% endfor %}
</select>

For textarea, you can use

<textarea>{{reqest.form.get("txt")}}</textarea>

or javascript

$('textarea').text('{{reqest.form.get("txt")}}')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM