Reputation: 43
I have a function that when you click the button it shows a form then it will add a card containing the data of the submitted form.
routes.py :
@app.route("/user", methods=['GET', 'POST'])
@login_required
def user():
form = BudgetForm()
budgets = Budgets.query.all()
return render_template("user.html", title=current_user.username, form=form, budgets=budgets)
@app.route("/add_budgets", methods=['GET', 'POST'])
def add_budgets():
form = BudgetForm()
if form.validate_on_submit():
budget = Budgets(budget=form.budget.data)
db.session.add(budget)
db.session.commit()
return redirect(url_for('user'))
return render_template("user.html", form=form)
forms.py:
class BudgetForm(FlaskForm):
budget = IntegerField('Budget', validators=[DataRequired(), NumberRange(min=100, max=1000000)])
submit = SubmitField('Submit')
models.py:
class Budgets(db.Model):
id = db.Column(db.Integer, primary_key=True)
budget = db.Column(db.Integer, nullable=False)
date_posted = db.Column(db.DateTime, nullable=False, default=datetime.utcnow)
budget_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)
expense = db.relationship('Expenses', backref='budget_expenses', lazy=True)
def __repr__(self):
return f"Budgets('{self.budget}')"
user.html :
<div class="dash-cards">
{% for budget in budgets %}
<div class="card-single">
<div class="card-body">
<span class="fas fa-coins"></span>
<div>
<h5>{{ budget.date_posted.strftime('%Y-%m-%d') }}</h5>
<h4>{{ budget.budget}}</h4>
</div>
</div>
<div class="card-footer">
<a href="">Add Expenses</a>
</div>
</div>
{% endfor %}
</div>
<div class="popup">
<div class="popup-content">
<form action="{{ url_for('add_budgets') }}" method="POST">
<div>
{{ form.budget.label(class="form-control-label", id="txt") }}
{{ form.budget(class="form-control") }}
</div>
<div class="form-group">
{{ form.submit(class="btn btn-outline-info" )}}
</div>
</form>
</div>
</div>
</main>
</div>
I also query in the command line but nothing shows up. There is no error when submitting form.
Upvotes: 1
Views: 148
Reputation: 931
I think you should refactor your add_budgets() function to look more like this:
def add_budgets():
form = BudgetForm()
if request.method == "POST":
if form.validate_on_submit():
budget = Budgets(budget=form.budget.data)
if budget:
db.session.add(budget)
db.session.commit()
return redirect(url_for('user'))
else:
# budget didn't get created
print("budget is {}".format(budget))
return render_template("user.html", form=form)
else:
return render_template("user.html", form=form)
My suspicion without trying the code is that your budget object is not getting created budget = Budgets(budget=form.budget.data)
. I hope this helps you figure it out.
Upvotes: 1