Adding permission based on the logged in user. Django

Viewed 55

How can i deny a user who did not create a post an ability to delete the post of another user and also how can i display various edit functions for a post based on the user? Meaning that if you are the creator of the post, only you can have access to editing that post. (for example, if you are logged in as the creator of the post, the post-view displays more options to edit/delete your post).

Can i create this permission through admin-groups or do i have to use another library?

views.py

def ViewPostMain(request, pk):

   post = Post.objects.get(id=pk)
   # where id is taken as the field name from the DB
   submissions = Submission.objects.filter(post_id = pk)
   # post_id is taken from db.

   context = {'post' : post, 'submissions' : submissions}

   return render(request, 'view-post.html', context)

view-post.html template

{% extends 'base.html' %}
{% block content %}



<h1><i> {{ post.title }} by {{post.author }}</i></h1>

{{ post.post_creation_time }}
{{ post.genre }}
{{ post.stage }}
{{ post.optional_notes }}


<div>
    <hr>
        <a href="{% url 'delete_post' post.id %}">(Delete Post)</a>
    <hr>

</div>



<h3><i>Submissions</i></h3>
<h6>{{ submissions.count }} submissions total  </h6>
<h3><i><a href="{% url 'create_submission' post.id %}">Create a submission</i></a></h3>


{% for submission in submissions reversed %}
    <ul>
        <p> post_id: {{ submission.post_id }}, submission id: {{ submission.id }} </p>
        <li> {{ submission.submission_title }} | {{ submission.submission_body }}, by {{     
submission.submission_author}} </li>
        <p> Submission for post: {{ submission.post.title }} </p>
    </ul>
{% endfor %}

<hr>

{% endblock %}
1 Answers

Assuming author is a FK to a User I'd do it like this;

views.py

def ViewPostMain(request, pk):

    try:
        post = Post.objects.get(id=pk)
    except Post.DoesNotExist:
        return Http404()

    # where id is taken as the field name from the DB
    submissions = Submission.objects.filter(post_id = pk)
    # post_id is taken from db.

    context = {
        'is_author': post.author == request.user,
        'post' : post,
        'submissions' : submissions
    }

    return render(request, 'view-post.html', context)

view-post.html template

{% if is_author %}
<div>
    <hr>
        <a href="{% url 'delete_post' post.id %}">(Delete Post)</a>
    <hr>
</div>
{% endif %}

Then you know that the user making the request is the author of the post and you can include whatever functionality you want in the if block.

Related