I am trying to make a calorie counter app using flask/python-anywhere, and part of it is making a drop down menu of foods to choose from. I want the user to be able to see the food name, but when they submit the food, it's the food's calories that I want to be added to the database.
This is the python code for the relevant tables:
class Post(db.Model):
__tablename__ = "posts"
id = db.Column(db.Integer, primary_key=True)
calories = db.Column(db.Integer)
timestamp = db.Column(db.DateTime, index=True, default=datetime.now)
consumer_id = db.Column(db.Integer, db.ForeignKey('users.id'), nullable=True)
consumer = db.relationship('User', foreign_keys=consumer_id)
class Food(db.Model):
__tablename__ = "foods"
id = db.Column(db.Integer, primary_key=True)
food_name = db.Column(db.String(200))
food_cal = db.Column(db.Integer)
This is the python code for the page:
@app.route("/", methods=["GET", "POST"])
@login_required
def index():
if request.method == "GET":
return render_template("main_page.html", foods=Food.query.all(), posts=Post.query.all(), timestamp=datetime.now())
if not current_user.is_authenticated:
return redirect(url_for('index'))
add_food = Post(calories=request.form["calories"], consumer=current_user)
db.session.add(add_food)
db.session.commit()
return redirect(url_for('index'))
and this is my html code:
<div class="container">
{% for post in posts %}
<div class="row" style="margin-bottom: 1ex">
<div>
You added {{ post.calories }} calories
</div>
<div>
<small>
at
{% if post.timestamp %}
{{ post.timestamp.strftime("%A, %d %B %Y at %H:%M") }}
{% else %}
at an unknown time
{% endif %}
</small>
</div>
</div>
{% endfor %}
{% if current_user.is_authenticated %}
<div class="row">
<form action="." method="POST">
<div class="form-group">
<label for="foods">Food:</label>
<select class="form control" name="food_name">
{% for food in foods %}
<option value = "{{ food.food_name }}" selected>{{ food.food_name }}</option>
{% endfor %}
</select>
<input type="submit" class="btn btn-success" value="Add calories">
</div>
</form>
</div>
{% endif %}
</div><!-- /.container -->
Just to clarify, the foods in the Food table have been added on my end, but I want the foods that users select to be saved as 'calories' in my Post table. Thanks in advance :)
<option value = "{{ food.food_name }}" selected>{{ food.food_name }}</option>
should be
<option value = {{ food.food_cal }} selected>{{ food.food_name }}</option>