如何将视图函数中的变量传递给jinja2模板 - Flask app

时间:2013-06-11 16:27:42

标签: python templates variables flask jinja2

我正在我的应用程序中编写一个基本的消息传递函数,它会按照它的设想执行。它在收件箱和发件箱中发送,接收和排序消息,我希望它显示发送者的昵称(TO:'昵称')和收到消息的人(来自:'昵称')

解决

class Message(db.Model):
    id = db.Column(db.Integer, primary_key = True)
    body = db.Column(db.String(140))
    timestamp = db.Column(db.DateTime)
    for_id = db.Column(db.Integer)
    **for_nickname = db.Column(db.String(140))**
    user_id = db.Column(db.Integer, db.ForeignKey('user.id'))
    def __repr__(self): # pragma: no cover
        return '<Message %r>' % (self.body)

我刚在表格中添加了一个昵称字段,因此我可以从发布的数据中访问它。我觉得再写2个查询并比较它们来获得相同的结果对于这样的事情来说太过分了。

编辑:

观点:

@app.route('/poraki', methods = ['GET', 'POST'])
@login_required
def poraki(page=1):
   form = PostMessage()
   nick = form.nickname.data
   nickname = User.query.filter_by(nickname = nick).first()
   if form.validate_on_submit():
    m = Message(body = form.post.data,
        timestamp = datetime.utcnow(),
        author = g.user,
        for_id = nickname.id)
    db.session.add(m)
    db.session.commit()
    flash(gettext(u'Вашата порака е пратена!'))
    return redirect(url_for('poraki'))
    #inbox
    sent = User.query.filter_by(nickname = g.user.nickname).first()
    all_inbox = Message.query.filter_by(for_id = sent.id).order_by(Message.timestamp.desc()).paginate(page, POSTS_PER_PAGE, False)
    #sent
    all_sent = Message.query.filter_by(user_id = sent.id).order_by(Message.timestamp.desc()).paginate(page, POSTS_PER_PAGE, False)

    return render_template('messages.html', form = form, posts1 = all_sent, posts2 = all_inbox, title = u'Пораки')

PostMessage的():

class PostMessage(Form):
    nickname = TextField('nickname', validators = [Required()])
    post = TextField('post', validators = [Required()])

message.html模板:

<td width="70px"><a href="{{url_for('user', nickname = post.author.nickname)}}"><img src="{{post.author.avatar(70)}}" /></a></td>
    <td>
        {% autoescape false %} 
        {% if prateni == 1 %}
        <p>{{ _('До: %(nickname)s ', nickname = '<a href="%s">%s</a>' % (url_for('user', nickname = post.for_id), post.for_id)) }}</p>
        {% else %}
        <p>{{ _('Од: %(nickname)s ', nickname = '<a href="%s">%s</a>' % (url_for('user', nickname = post.author.nickname), post.author.nickname)) }}</p>
        {% endif %}
        {% endautoescape %}
        <p><strong><span id="post{{post.id}}">{{post.body}}</span></strong></p>
        {% autoescape false %}
        <p>{{ _('%(when)s', when = momentjs(post.timestamp).fromNow() ) }} </p>
        {% endautoescape %}

        <!-- {% if post.author.id == g.user.id %}
        <div><a href="{{ url_for('delete', id = post.id) }}">{{ _('Избриши') }}</a></div>
        {% endif %} -->
    </td>

messages.html模板:

<div class="well">
<form class="form-horizontal" action="" method="post" name="post">
    {{form.hidden_tag()}}
    <div class="control-group{% if form.errors.post %} error{% endif %}">
        <label class="control-label" for="nickname">{{ _('До:') }}</label>
        <div class="controls">
            {{ form.nickname(size = 30, maxlength = 140) }}
            {% for error in form.errors.nickname %}
                <span class="help-inline">[{{error}}]</span><br>
            {% endfor %}
        </div>
    </div>
    <div class="control-group{% if form.errors.post %} error{% endif %}">
        <label class="control-label" for="post">{{ _('Порака:') }}</label>
        <div class="controls">
            {{ form.post(cols = 64, rows = 4, class = "span4") }}
            {% for error in form.errors.post %}
                <span class="help-inline">[{{error}}]</span><br>
            {% endfor %}
        </div>
    </div>
    <div class="control-group">
        <div class="controls">
            <input class="btn btn-primary" type="submit" value="{{ _('Прати!') }}">
        </div>
    </div>
</form>
</div>
<table class="table">
<tr>

<td width=50%> Пратени пораки {{ proba }}
{% set prateni = 1 %}
{% for post in posts1.items %}
    {% include 'message.html' %}
{% endfor %}
</td width=50%>
<td> Примени пораки
{% set prateni = 0 %}
{% for post in posts2.items %}
    {% include 'message.html' %}
{% endfor %}
</td>
</tr>
</table>

0 个答案:

没有答案