Blog with Django (Codemy.com) - 16 How to Determine the Correct User to Edit Posts

이다연·2021년 3월 31일
0

Django

목록 보기
23/33

Logic: Compare the current user and author(user who created the post)

author is connected to User model as foreign key

author's id:{{post.author.id}}
current user: {{user.id}}

Use if statement

1. post_detail.html

{% if user.is_authenticated %}
    {% if user.id == post.author.id %}
        < a href="{% url 'update_post' post.pk %}" class="btn btn-sm btn-secondary"> Edit </a>
        < a href="{% url 'delete_post' post.pk %}" class="btn btn-sm btn-secondary"> Delete </a></small>
    {% endif %}
{% endif %}

2. update_post.html

Even though people cannot see the edit button, if they know the address, they can still access to editing page.
To prevent that happens, add if statement to update_post.html too.

{% if user.is_authenticated %}
        {% if user.id == post.author.id %}
<h1> Update Post  </h1>
<br/>

<div class="form-group">
    <form method="POST">
        {% csrf_token %}
        {{ form.as_p }}
        <br/>
        <button class="btn btn-secondary"> Update </button>
    </form>
</div>
{% else %}
You are not allowed here. Please log in.

    {% endif %}
{% endif %}

if I try to edit bob's post, it doesn't allow me.

3. apply if statement to any pages that's applicable

for example

home
delete...

profile
Dayeon Lee | Django & Python Web Developer

1개의 댓글

comment-user-thumbnail
2024년 3월 27일

Your information is so useful for me to determine the correct user to edit posts in uno online. I have many posts in this website, so I'm so happy.

답글 달기