我的models.py中有两个类(用户和日记)。用户包含有关用户的详细信息,日记包含带有注释的情感。当我尝试使用用户对象遍历日记时,该用户对象是使用for循环的列表,它进入无限循环,不会显示结果
models.py
from datetime import date
from flaskblog import db, login_manager
from flask_login import UserMixin
@login_manager.user_loader
def load_user(user_id):
return User.query.get(int(user_id))
class User(db.Model, UserMixin):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(20), unique=True, nullable=False)
email = db.Column(db.String(120), unique=True, nullable=False)
password = db.Column(db.String(60), nullable=False)
diaries = db.relationship('Diary', backref='author', lazy=True)
def __repr__(self):
return f"User('{self.username}', '{self.email}')"
class Diary(db.Model):
id = db.Column(db.Integer, primary_key=True)
diary_date= db.Column(db.DateTime, nullable=False, default=date.today())
emotion = db.Column(db.String(10))
note = db.Column(db.Text)
user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)
def __repr__(self):
return f"Diary('{self.diary_date}', '{self.emotion}','{self.note}')"
routes.py我正在使用日记的地方
@app.route("/account", methods=['GET', 'POST'])
@login_required
def account():
diaries=Diary.query.all()
form = UploadImage()
#picture_file=save_picture(form.picture.data)
if request.method == 'POST':
file = request.files[form.picture.name]
note=Diary(diary_date=date.today(), note=form.note.data, author=current_user)
db.session.add(note)
db.session.commit()
if file:
filename = secure_filename(file.filename)
file.save(os.path.join(app.root_path, 'static/pics', filename))
image_file = url_for('static', filename='pics/' + filename)
return render_template('account.html', title='Account',image_file=image_file, form=form)
#filename = 'http://localhost:5000/account' + filename
#return render_template('account.html', filename = filename,form=form)
return render_template('account.html', title='Account',form=form)
account.html
{% for diary in diaries %}
<div class="article-metadata">
<h2>{{ diary.author.username }}</h2>
<h2>{{ diary.diary_date.strftime('%Y-%m-%d') }}</h2>
<h2>{{ diary.emotion }}</h2>
<h2>{{ diary.note }}</h2>
</div>
{% endfor %}
此后,屏幕上没有任何打印内容。我尝试使用cmd并在db上使用相同的循环。它陷入无限循环
>>> user
User('hannah baker', 'baker.hannahkillme@gmail.com')
>>> diaries=Diary.query.all()
>>> diaries
[Diary('2019-01-28 00:00:00', 'None','Nothing specific happened today'), Diary('
2019-01-28 00:00:00', 'None','Day spent well'), Diary('2019-01-28 00:00:00', 'None','My college sucks')]
>>> for diary in diaries:
... print(diary.note)
...
它应该打印我有的笔记
答案 0 :(得分:0)
您需要将diaries
传递给render_template
return render_template('account.html', title='Account',form=form, diaries=diaries)