python – Flask how do I get a list of posts for a specific user?

Question:

I have two models: 1) User 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))

2) Record Model:

с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'))

There is also a user view:

@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)

And the view for adding a record:

@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)

user pattern:

{% for post in posts %}
    <p>{{ entry.title }}</p>
    <pre>{{ entry.text }}</pre>
    <p>{{ entry.pub_date }}</p>
{% endfor %}

Post adding template:

{% block content %}
<form class=login-form method=post action=add>
<h1 align=center>Заполните поля, для регистрации вашего стиха:</h1>
    <p>
    {{ form.hidden_tag() }}
    <div class=field>
    <p>{{ form.title.label }}:</p> <p>{{ form.title(size=25) }}</p>
    {% for error in form.errors.title %}
        <br><span style="color: red;">[{{ error }}]</span>
    {% endfor %}

    <div class=field>
    <p>{{ form.text.label }}:</p> <p>{{ form.text(cols=35, rows=20) }}
</p>
    {% for error in form.errors.text %}
        <br><span style="color: red;">[{{ error }}]</span>
    {% endfor %}
    </div>

    <div class=field>
    <p>{{ form.pub_date.label }}:</p> <p>{{ form.pub_date(size=20) }}</p>
        <input type="submit" value="Разместить стих">
    </div>
</form>
{% endblock %}

So the question is, how do I get the list of entries? How to bind records to a user through a view?

Answer:

It is necessary to add an entry to the parent table, it can be done somehow like this (I use the ORM of Alchemy a little differently):

@app.route('/add/<nickname>', methods=['GET', 'POST'])
@login_required
def add(nickname):
    title = 'Добавление стиха'
    form = EntryForm()
    if form.validate_on_submit():
        user = User.query.filter_by(nickname=nickname).first()
        if not user:
            flash('Пользователь ' + nickname + ' не найден.')
            return redirect(url_for('index'))
        add_entry = Entry(form.title.data, form.text.data, form.pub_date.data)
        user.posts.append(add_entry)
        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)

http://docs.sqlalchemy.org/en/latest/orm/basic_relationships.html#association-object

Scroll to Top
AllEscort