Home > Blockchain >  Pre-Populating HTML form, date, with Flask variable content
Pre-Populating HTML form, date, with Flask variable content

Time:12-23

I am working with a simple csv file which has 1 row, no header, containing two fields (both dates). The below Python script and HTML works so far, but I can nOT get the date fields to be populated with the cell content of the csv before the user (me) can change the date. I have been trying for days now.

HTML (form.html):

<form action="{{ url_for("getdates")}}" method="post">
<label for="first">1st Ferment Date:</label>
<input type="date" id="first" name="first" placeholder="first" value=firsttrial>
{{ firsttrial }}
<br>
<br>
<label for="bottled">Bottling Date:</label>
<input type="date" id="bottled" name="bottled" placeholder="bottled">
<br>
<br>
<button type="submit">click here to Reset</button>
Python/Flask code (getdates.py)"

from flask import Flask, request, render_template 
import os
import csv
app = Flask(__name__)   

dir = os.path.dirname(__file__)
with open(dir 'Data/variable.csv') as f:
    data = list(csv.reader(f))
    print('after list(csv.reader)'   data[0][0])
    firsttrial = data[0][0]
    #try:
    #    last_name = data[0][1]
    #except:
    #    print("not working")
    #else:
    #    print("last" last_name)

f.close()


@app.route('/', methods =["GET", "POST"])
def getdates():
    templateData = {
            'firsttrial' : firsttrial
            }
    if request.method == "POST":
       # getting input with name = fname in HTML form
        first = request.form.get("first")
        if first:
            # getting input with name = lname in HTML form 
            bottled = request.form.get("bottled") 
            input_dictionary = bottled
            dir = os.path.dirname(__file__)
            tempsfile = dir   "Data/variable.csv"
            import csv
            RESULT = [first, bottled]
            resultFile = open(tempsfile,'w')
            wr = csv.writer(resultFile, dialect='excel')
            wr.writerow(RESULT)
            resultFile.close()
        else:
            return "you did not enter the word 'reset', so counter will continue as is"
    return render_template("form.html",**templateData)
  
if __name__=='__main__':
    app.run()

Any help would be appreciated!

CodePudding user response:

This:

<input type="date" id="first" name="first" placeholder="first" value=firsttrial>
{{ firsttrial }}

should be this:

<input type="date" id="first" name="first" placeholder="first" value="{{firsttrial}}">

It's the value attribute that specifies what gets placed in the field.

  • Related