I am not able to add data to the database, below is my code:
from flask import Flask, render_template, request, redirect
from flask_sqlalchemy import SQLAlchemy
from datetime import datetime
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///friends.db'
db = SQLAlchemy(app)
class Friends(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(10), nullable=False)
date_created = db.Column(db.DateTime, default = datetime.utcnow)
def __repr__(self):
return '<name %r>'& self.id
@app.route('/friends', methods=['POST', 'GET'])
def friends():
if request.method == "POST":
friend_name = request.form['name']
new_friend = Friends(name=friend_name)
try:
db.session.add(new_friend)
db.session.commit()
return redirect('/friends')
except:
return "friend could not be added"
else:
friends = Friends.query.order_by(Friends.date_created)
return render_template("friends.html", title = title, friends = friends)
friends.html:
<form action="/friends" METHOD="POST">
<input type="text" name= "name" placeholder="enter name">
<input type="submit" value="Add name" class="btn btn-secondary">
</form>
{% for friend in friends %}
<li>{{friend}}</li>
{% endfor %}
The first error i am getting is
TypeError: unsupported operand type(s) for &: 'str' and 'int'
When I delete Self.id
, it works however the friend list is added to the database under <name %r>
and not the name which was added in the form. I know that I did something wrong but I am not able to find it.
i should have added {{friend.name}} instead of {{friend}}.
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.