Python Flask将下拉值输出到pag

2024-09-30 18:12:43 发布

您现在位置:Python中文网/ 问答频道 /正文

我有两个字典,有几个键,每个键有一个值。一个dict有每周累计工作时间,另一个dict有每周累计加班时间。键是一个datetime对象,它被计算为一周的开始。在我的网页上我有一个下拉框,其中包含了一周的开始

  <form action="{{ url_for('index') }}" method="post">
    <select class="form-control" name="cumuls" id="select1" onchange="if(this.value != 0) { this.form.submit(); }">
        <option value="0">Cumulative for week beginning...</option>
        {% for i,j in zip(wks, wks2) %}
        <option value="{{ i }}">{{ j }}</option>
        {% endfor %}
    </select>
  </form>

wks2只是wks的一个格式很好的版本,wks只是dict中的键列表,dict是datetime对象(字典有相同的键))

我希望能够从下拉框中单击一个选项,并使两个字典中的相应值显示在下拉框下方。你知道吗

我在这里处理表单(在index()函数中),在if是index函数的结尾之后:

if request.method == 'POST':
    if 'cumuls' in request.form:
        week_Begin = request.form['cumuls']
        listHours = listDates(current_user.get_id())
        dct_hours, dct_overtime, wks = weeklySum2(listHours)

        #strfdelta is a custom function that formats timedeltas
        cumul_hrs = strfdelta(dct_hours[datetime.fromisoformat(week_Begin)], '%H:%M')

        cumul_overtime = strfdelta(dct_overtime[datetime.fromisoformat(week_Begin)], '%H:%M')

        return redirect(url_for('index'))

listHours = listDates(current_user.get_id())

dct_hours, dct_overtime, wks = weeklySum2(listHours)
print(wks)
# wkbgn = weekbeginning, this just formats the dates nicely
wks2 = [wkbgn.strftime('%A') + ' ' + wkbgn.strftime('%-d') + ' ' + wkbgn.strftime('%b') + ' ' + wkbgn.strftime('%Y') for wkbgn in wks]

currentDay = datetime.today()
start_week = (currentDay - timedelta(days=currentDay.weekday()))

return render_template('index.html', form=form, hoursDb = listHours, dct_overtime=dct_overtime,dct_hours=dct_hours, wks=wks, wks2=wks2, zip=zip)

所以在if 'cumuls'...中,我基本上得到了所选周的累计工作时间和加班时间,在cumul_hrscumul_overtime中,这是有效的。我基本上希望这些变量显示在网页上(在下拉框下面),并且显示的默认变量将是到目前为止累计的当前周数。我怎么能这么做?你知道吗

非常感谢您的指点/提示。你知道吗


Tags: formfordatetimeindexif时间dictdct
1条回答
网友
1楼 · 发布于 2024-09-30 18:12:43

最后我把elif语句中的重定向改为

return redirect(url_for('index', cumul_hrs=cumul_hrs, cumul_overtime=cumul_overtime))

然后从URL获取变量:

cumul_hrs, cumul_overtime = request.args.get('cumul_hrs'), request.args.get('cumul_overtime')

把它们通过render_template。你知道吗

相关问题 更多 >