【问题标题】:Pre-Populating HTML form, date, with Flask variable content使用 Flask 变量内容预填充 HTML 表单、日期
【发布时间】:2022-01-23 23:09:09
【问题描述】:

我正在使用一个简单的 csv 文件,它有 1 行,没有标题,包含两个字段(两个日期)。到目前为止,下面的 Python 脚本和 HTML 工作正常,但在用户(我)可以更改日期之前,我无法使用 csv 的单元格内容填充日期字段。 我已经尝试了好几天了。

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()

任何帮助将不胜感激!

【问题讨论】:

    标签: python html flask


    【解决方案1】:

    这个:

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

    应该是这样的:

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

    value 属性指定放置在字段中的内容。

    【讨论】:

    • 总救星!!!!!! TY VM 蒂姆
    猜你喜欢
    • 2015-06-24
    • 2016-06-24
    • 2016-06-23
    • 1970-01-01
    • 1970-01-01
    • 2022-11-01
    • 1970-01-01
    • 2013-02-05
    • 2018-08-15
    相关资源
    最近更新 更多