简体   繁体   English

根据登录用户添加权限。 姜戈

[英]Adding permission based on the logged in user. Django

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视图.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 view-post.html 模板

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

Assuming author is a FK to a User I'd do it like this;假设authorUser的 FK,我会这样做;

views.py视图.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 view-post.html 模板

{% 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.然后您知道发出请求的用户是帖子的作者,您可以在if块中包含您想要的任何功能。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM