Blog with Django (Codemy.com) - 16 How to Determine the Correct User to Edit Posts
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...
Author And Source
이 문제에 관하여(Blog with Django (Codemy.com) - 16 How to Determine the Correct User to Edit Posts), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://velog.io/@daylee/Blog-with-Django-Codemy.com-1617-How-to-Determine-the-Correct-User-to-Edit-Posts저자 귀속: 원작자 정보가 원작자 URL에 포함되어 있으며 저작권은 원작자 소유입니다.
우수한 개발자 콘텐츠 발견에 전념 (Collection and Share based on the CC Protocol.)