Я использую flask -wtf. У меня есть selectmultiplefield, который я хочу, чтобы пользователь мог загружать и видеть выбранные значения по умолчанию для. в идеале я хочу, чтобы пользователь мог изменить выбор по умолчанию и щелкнуть по кнопке «Отправить», после чего будет отображен тот же шаблон, но с новыми вариантами выбора по умолчанию. Я включил свой код ниже, и вы увидите, что в настоящее время я пытаюсь обойти эту проблему, отправив их на страницу «success», которая называется countrylist. html сначала, чтобы показать им их выбор, а затем позволить им выбрать go и сделать новые изменения ... Я думал, что этот обходной путь покажет новые значения по умолчанию, но в форме просто не будут отображаться новые обновления, пока я не перезапущу сервер httpd, и в этом случае он просто подберет новые значения по умолчанию. Я предполагаю, что мне нужно передать значения по умолчанию, когда я вызываю "form = CountryForm ()", но ничего из того, что я пробовал, не сработало. Любая помощь будет оценена. У меня нет идей ... есть пара других похожих статей, но они не привели меня к решению моей конкретной проблемы. Спасибо за ваше внимание
##################### forms.py ##############################
from flask_wtf import FlaskForm
from wtforms import StringField, SelectField, PasswordField, BooleanField, SubmitField, RadioField, FileField, SelectMultipleField
from wtforms.validators import DataRequired, InputRequired, Optional, Regexp, Length
from sqlalchemy import create_engine
import os
class CountryForm(FlaskForm):
countries = []
# open file and read the content in a list
with open('/var/www/dashboard/app/static/uploads/lists/country_list.txt', 'r') as filehandle:
for line in filehandle:
# remove linebreak which is the last character of the string
currentPlace = line[:-1]
# add item to the list
countries.append(currentPlace)
country_list = SelectMultipleField('Blocked Countries', default=countries, choices=[('AF','Afghanistan'), ('AL','Albania'), ('DZ','Algeria'), ('AS','American Samoa')], validators=[InputRequired()])
submit = SubmitField('Submit')
################### routes.py #################################
from flask import render_template, flash, redirect, url_for, request
import json
from app import app
from app.forms import LoginForm, SettingsForm, AlertsForm, CountryForm
from sqlalchemy import create_engine
from flask_uploads import UploadSet, configure_uploads, TEXT, UploadNotAllowed
from werkzeug.exceptions import HTTPException
import os
@app.route('/country', methods=['GET', 'POST'])
def country():
form = CountryForm()
if form.validate_on_submit():
country_list_list = form.country_list.data
if len(country_list_list) > 0:
with open('/var/www/dashboard/app/static/uploads/lists/country_list.txt', 'w') as filehandle:
for listitem in country_list_list:
filehandle.write('%s\n' % listitem)
form = CountryForm()
return redirect('countrylisted')
else:
return render_template('country.html', title='Country', form=form)
@app.route('/countrylisted', methods=['GET', 'POST'])
def countrylisted():
form = CountryForm()
# open file and read the content in a list
countries = []
with open('/var/www/dashboard/app/static/uploads/lists/country_list.txt', 'r') as filehandle:
for line in filehandle:
# remove linebreak which is the last character of the string
currentPlace = line[:-1]
# add item to the list
countries.append(currentPlace)
return render_template('countrylisted.html', title='Country', countries=countries)
####################### country.html #######################
{% extends "base.html" %}
{% block content %}
<h3>Country list</h3>
<form action="{{ url_for('country') }}" method="post" novalidate>
{{ form.csrf_token }}
{{ form.hidden_tag() }}
<p>
{{ form.country_list.label}}<br>
{{ form.country_list(size=20, multiple=True) }}<br>
{% for error in form.country_list.errors %}
<span style="color: red;">[{{ error }}]</span>
{% endfor %}
</p>
<p>{{ form.submit() }}</p>
</form>
{% endblock %}
####################### countrylist.html #############################
{% extends "base.html" %}
{% block content %}
<h3>Countries</h3>
{% for country in countries %}
<h5>{{country}}</h5><BR>
{% endfor %}
<a href="http://52.141.219.173/country">Change the Countries on this list</a>
{% endblock %}