Heidi Lily Pak Heidi Lily Pak - 4 months ago 9
MySQL Question

Python - Show delete button only if user owns post

EDIT: Problem solved! Thank you to user limbo for your input. It was not the solution, but led me down right path: my LEFT JOIN was showing all null posts! I have also included the if-defined check, as a good back-up check.

Goal: On a message post dashboard, only show delete-post button if the logged-in user owns that post.

What works: Button will display & function correctly if user has created a post into database.

What fails: If user does not have a post in database, the dashboard displays a 'template' post that holds no value and is not in the database. On all users' dashboards, this 'template' post associated with the non-posting user is visible. Once the user creates a post into database, this 'template' will disappear and delete button shows correctly. If I delete the user's last (or only) post, this 'template' post will reappear.

What I think: Something is wrong with my 'if' statement? Since it displays this 'template' post for every single user who does not have any real posts, regardless of who I'm logged in as.

Here is my code for

, abbreviated.

{% 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

{% endfor %}

, with query abbreviated--just in case it's related.

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

Thank you!


I think what you need to do is check if the messages are real before displaying them.

Assuming you are using jinja2 you need to insert this {% if messages is defined %} before {% for message in messages: %} to check that the messages collection is not empty.

Of course don't forget to close your if {% endif %} at the end.