【问题标题】:Python - Show delete button only if user owns postPython - 仅当用户拥有帖子时才显示删除按钮
【发布时间】:2016-06-03 20:17:46
【问题描述】:

编辑:问题解决了!感谢用户limbo的输入。这不是解决方案,但让我走上了正确的道路:我的 LEFT JOIN 显示所有空帖子!我还包括了 if-defined 检查,作为一个很好的备份检查。

目标:在消息发布仪表板上,仅当登录用户拥有该帖子时才显示删除发布按钮。

工作原理:如果用户在数据库中创建了帖子,按钮将正常显示和运行。

什么失败:如果用户在数据库中没有帖子,仪表板会显示一个“模板”帖子,该帖子没有价值并且不在数据库中。在所有用户的仪表板上,与非发帖用户关联的这个“模板”帖子都是可见的。用户在数据库中创建帖子后,此“模板”将消失,删除按钮将正确显示。如果我删除用户的最后(或唯一)帖子,此“模板”帖子将重新出现。

我的想法:我的“if”语句有问题吗?因为它为没有任何真实帖子的每个用户显示此“模板”帖子,无论我以谁身份登录。

这是我的dashboard.html 代码,缩写。

    {% for message in messages: %}
        //'mu_id' is messages.user_id as defined in server.py
        //'user[0]['id'] is logged-in user id
        //using 'session['id'] instead produces same (unwanted) results 

        {% if message['mu_id'] == user[0]['id']: %}
            // show delete button (this part worked, don't worry)
        {% endif %}

        //this displays each message with poster name
        {{message['first_name']}}<br>
        {{message['message']}} 

    {% endfor %}

我的server.py,查询缩写——以防万一。

//this query uses session['id'] to grab user data
query = "SELECT * FROM users WHERE id = :id LIMIT 1"
data = {
    'id': session['id']
}
user = mysql.query_db(query, data)

// this query joins messages & users tables
mquery = "SELECT first_name, message, messages.id AS message_id, messages.user_id AS mu_id FROM users LEFT JOIN messages ON users.id = messages.user_id"
messages = mysql.query_db(mquery)

//Long query here to get comments, by joining messages & users table to comments table. 

return render_template('dashboard.html', user=user, messages=messages, comments=comments)

谢谢!

【问题讨论】:

  • 这不是 django 吗?如果您使用 django,为什么要使用 mysql 库?
  • 我正在学习一个使用 Flask/MySQL/Python 的教程,但还没有被介绍给 django。
  • 这似乎不是一个好的教程

标签: python mysql button


【解决方案1】:

我认为您需要做的是在显示消息之前检查消息是否真实。

假设您使用的是 jinja2,您需要在 {% for message in messages: %} 之前插入此 {% if messages is defined %} 以检查消息集合是否为空。

当然不要忘记在最后关闭你的 if {% endif %}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-09
    • 1970-01-01
    相关资源
    最近更新 更多