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?
- View customer page
- Click "Add Customer" > taken to "add_customer" route
- Add customer info and click submit
- Customer page is updated correctly with latest customer name
- View Projects page
- Click "Add Project" > taken to "add_project" route
- This page has a dropdown box for list of customer but does not include the last customer I created or any customers I have created since I last started flask.
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 %}