Answer the question
In order to leave comments, you need to log in
Flask how do I get a list of a particular user's posts?
I have two models:
1) Users model
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
nickname = db.Column(db.String(100), index=True, unique=True)
email = db.Column(db.String(120), index=True, unique=True)
password = db.Column(db.String(100), index=True, unique=True)
role = db.Column(db.SmallInteger, default=ROLE_USER)
posts = db.relationship('Entry', backref='author', lazy='dynamic')
about_me = db.Column(db.String(140))
last_seen = db.Column(db.DateTime)
pwdhash = db.Column(db.String(100))
сlass Entry(db.Model):
id = db.Column(db.Integer, primary_key=True)
title = db.Column(db.String(80))
text = db.Column(db.Text)
pub_date = db.Column(db.DateTime)
user_id = db.Column(db.Integer, db.ForeignKey('user.id'))
@app.route('/user/<nickname>', methods=['GET', 'POST'])
@login_required
def user(nickname):
title = 'Ваша страница'
user = User.query.filter_by(nickname=nickname).first_or_404()
if user == None:
flash('Пользователь ' + nickname + ' не найден.')
return redirect(url_for('index'))
post = user.posts.order_by(Entry.pub_date.desc()).all()
return render_template('user.html', title=title, user=user, post=post)
И вьюшка добавления записи:
@app.route('/add', methods=['GET', 'POST'])
@login_required
def add():
title = 'Добавление стиха'
form = EntryForm()
if form.validate_on_submit():
add_entry = Entry(form.title.data, form.text.data, form.pub_date.data)
db.session.add(add_entry)
db.session.commit()
flash('Вы добавили новый стих') return redirect(url_for('user', nickname=g.user.nickname))
return render_template('entry.html', title=title, form=form)
{% for post in posts %}
<p>{{ entry.title }}</p>
<pre>{{ entry.text }}</pre>
<p>{{ entry.pub_date }}</p>
{% endfor %}
{% block content %}
Заполните поля, для регистрации вашего стиха:
{{ form.hidden_tag() }}
{{ form.title.label }}: {{ form.title(size=25) }}
{% for error in form.errors.title %} [{{ error }}] {% endfor %}
{{ form.text.label }}: {{ form.text(cols=35, rows=20) }}
{% for error in form.errors.text %} [{{ error }}] {% endfor %}
{{ form.pub_date.label }}: {{ form.pub_date(size=20) }}
{% endblock %}
Answer the question
In order to leave comments, you need to log in
post = user.posts.order_by(Entry.pub_date.desc()).all()
post
, but in the template posts
. author
in Entry
:add_entry = Entry(
title=form.title.data,
text=form.text.data,
pub_date=form.pub_date.data,
author=g.user
)
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question