I have a flask web app with a Customer page and a Project Page. This is the workflow and where it goes wrong. Any ideas where I might have gone wrong?
If I restart flask, the dropdown box contains the latest customers. At first I thought I was not committing the database, but it seems like I am with the db.session.commit below. I posted relevant code, let me know if you want to see anything else.
I can't seem to find my particular issue on the web, most of what I find pertains to filling in the dropdown box itself, which does work.
forms.py:
class AddProjectForm(FlaskForm):
projectname = StringField('Project Name', validators=[DataRequired()])
customer_query = Customer.query.all()
customers = []
for c in customer_query:
customers.append(c.customername)
customers = SelectField('Customer', choices=customers, default=1)
submit = SubmitField('Add Project')
routes.py:
@app.route('/add_customer', methods=['GET', 'POST'])
@login_required
def add_customer():
customer = Customer.query.all()
form = AddCustomerForm()
if request.method == 'POST':
customername = request.values.get('customername')
c = Customer(customername=customername)
db.session.add(c)
db.session.commit()
return redirect(url_for('customer'))
return render_template("add_customer.html", title='Add a Customer', form=form)
@app.route('/add_project', methods=['GET', 'POST'])
@login_required
def add_project():
form = AddProjectForm()
if request.method == 'POST':
projectname = request.values.get('projectname')
customer = request.values.get('customers')
customer_id = Customer.query.filter_by(customername=customer).first().id
project = Project(projectname=projectname,customer_id=customer_id)
db.session.add(project)
db.session.commit()
return redirect(url_for('projects'))
return render_template("add_project.html", title='Add a Project', form=form)
add_project.html
{% extends "base.html" %}
{% block content %}
<h1>Add a Project</h1>
<form action="" method="post">
{{ form.hidden_tag() }}
<p>
{{ form.projectname.label }}<br>
{{ form.projectname }}<br>
</p>
<p>
{{ form.customers.label }}<br>
{{ form.customers }}<br>
</p>
<p>
{{ form.submit() }}
</p>
</form>
{% endblock %}
Found the answer here:
Flask WTF form not updating with the sqlite3 database
I removed the customer list population from the Form and added it to the view. Then passed the customer list to the template, and updated template like this.
add_project.html
<select name="customer" id="customer">
{% for customer in customers %}
<option value="{{ customer }}">{{ customer }}</option>
{% endfor %}
</select>
Now it's working.
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.