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

4167 단어 djangodjango

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...

좋은 웹페이지 즐겨찾기